比较数组多维PHP

时间:2018-08-24 07:42:37

标签: php arrays 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 ) )

我想比较使用[0] [0]小于或大于[0] [1],然后比较[1] [0]与[1] [1],依此类推。我对多维数组不满意

2 个答案:

答案 0 :(得分:2)

尝试一下:

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

输出:

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

答案 1 :(得分:0)

您可以像这样循环遍历第一个数组:

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

然后在该循​​环中,您可以访问每个单独的数组。因此,您可以在其中执行以下操作:

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';
}

因此,您的总代码应如下所示:

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';
    }
}