tags:

views:

1267

answers:

2

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

$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)

Thanks in advance

+1  A: 
<?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.

belunch
I'd like to comment that this approach can break unless you have a completely rectangular 2d array. as the input.
Peter Bailey
why do you do $ret[count($ret)+1] = $row[$col]; What's wrong with $ret[] = $row[$col];
Tom Haigh
tom: I just tried to add element at the very end of the $ret array. I did not know $ret[] notation :D BaileyP: unsure of what would be the break condition - input array has 3 elements, every element is a 4 element array.
belunch
+1  A: 

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] );
Peter Bailey