简体   繁体   中英

Compare Array multidimensional PHP

I have an Multidimensional Array.

Array ( 
[0] => Array ( 
    [0] => 116.01 
    [1] => 146.00 ) 
[1] => Array ( 
    [0] => 92.00 
    [1] => 122.02 ) 
[2] => Array ( 
    [0] => 308.00 
    [1] => 278.00 ) )

I want to compare using less than or greater than, [0][0] with [0][1] and then [1][0] with [1][1] and so on. I'm dummy with multidimensional array

Try this :

$arr = [ [116.01, 146.00], [92.00, 122.02], [308.00, 278.00] ];
$res = array_map(function($v) {return "first > second ? " 
                                      . ($v[0] > $v[1] ? 'YES' : 'NO');}, $arr);
var_dump($res);

Outputs :

array(3) {
  [0]=>
  string(19) "first > second ? NO"
  [1]=>
  string(19) "first > second ? NO"
  [2]=>
  string(20) "first > second ? YES"
}

You could loop through your first array like so:

foreach ($array as $key => $subArray) {
    //do stuff
}

Then inside that loop you have access to each individual array. So in there you could do something like this:

if ($subArray[0] < $subArray[1]) {
    echo '1 is biggest';
} elseif ($subArray[0] > $subArray[1]) {
    echo '0 is biggest';
} else {
    echo '1 and 0 are equal';
}

So your total code would look something like this:

foreach ($array as $key => $subArray) {

    echo 'For array with key ' . $key . ':';

    if ($subArray[0] < $subArray[1]) {
        echo '1 is biggest';
    } elseif ($subArray[0] > $subArray[1]) {
        echo '0 is biggest';
    } else {
        echo '1 and 0 are equal';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM