使用PHP在数组上使用MAX和MIN值

时间:2022-02-28 07:48:29

Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?

有谁知道如何在PHP中获得第2和第3列的最大值和最小值?

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

Output should be like:

输出应该像:

max(12.9) min(10)

2 个解决方案

#1


1  

<?php
$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));
function col($tbl,$col){
    $ret = array();
    foreach ($tbl as $row){
        $ret[count($ret)+1] = $row[$col];
    }
    return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>

is this what you look for? I guess its not the most efficient way.

这是你要找的?我猜它不是最有效的方式。

#2


2  

Another option

<?php

function array_rotate( $array )
{
    $rotated = array();
    foreach ( $array as $rowIndex => $col )
    {
        foreach ( $col as $colIndex => $value )
        {
            $rotated[$colIndex][$rowIndex] = $value;
        }
    }
    return $rotated;
}

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

$ar = array_rotate( $ar );

echo max( $ar[2] ), "\n", min( $ar[1] );

#1


1  

<?php
$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));
function col($tbl,$col){
    $ret = array();
    foreach ($tbl as $row){
        $ret[count($ret)+1] = $row[$col];
    }
    return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>

is this what you look for? I guess its not the most efficient way.

这是你要找的?我猜它不是最有效的方式。

#2


2  

Another option

<?php

function array_rotate( $array )
{
    $rotated = array();
    foreach ( $array as $rowIndex => $col )
    {
        foreach ( $col as $colIndex => $value )
        {
            $rotated[$colIndex][$rowIndex] = $value;
        }
    }
    return $rotated;
}

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

$ar = array_rotate( $ar );

echo max( $ar[2] ), "\n", min( $ar[1] );