简体   繁体   English

如何在给定范围内搜索多维数组中的最大值

[英]How to search for the maximum value in a multidimensional array in a given range

I have a multidimensional $array that has a lot of various values. 我有一个多维$array ,它具有很多不同的值。 I am trying to get the maximum value in a given range in this case lets say the maximum value within x1,y0 and x2,y7, thus the result would be 6 using the data below. 我正在尝试在给定范围内获得最大值,在这种情况下,可以说x1,y0和x2,y7内的最大值,因此使用以下数据将得出6

It seems like a common problem for searching within coordinates in multidimensional array... but I cant find a simple solution and everything that I try to do seems to be rather extensive in the coding. 在多维数组中的坐标内搜索似乎是一个普遍的问题……但是我找不到简单的解决方案,而且我尝试做的所有事情似乎在编码中都相当广泛。 I was wondering if there is a function that would allow me to search in this array using my criteria in an efficient way. 我想知道是否有一个函数可以让我有效地使用自己的条件在此数组中进行搜索。

$array[0][0] = 1;
$array[0][1] = 10;
$array[0][3] = 3;
$array[1[0] = 1;
$array[1][1] = 1;
$array[2][5] = 6;
$max = null;
for ($x = $startx; $x <= $endx; $x++) {
    for ($y = $starty; $y <= $endy; $y++) {
        if (isset($array[$x][$y]) && ($max === null || $array[$x][$y] > $max)) {
            $max = $array[$x][$y];
        }
    }
}
$array[0][0] = 1;
$array[0][1] = 10;
$array[0][3] = 3;
$array[1][0] = 1;
$array[1][1] = 1;
$array[2][5] = 6;

$max = false;
$x1 = 1; $x2 = 2;
$y1 = 0; $y2 = 7;

foreach($array as $x => $y_vals) {    
    if($x < $x1 || $x > $x2)
        continue;

    foreach($y_vals as $y => $val) {
        if($y < $y1 || $y > $y2)
            continue;

        if(false === $max || $max < $val)
            $max = $val;
    }
}

print $max; //6
$array[0][0] = 1;
$array[0][1] = 10;
$array[0][3] = 3;
$array[1][0] = 1;
$array[1][1] = 1;
$array[2][5] = 6;

$vals = array();
foreach (new RecursiveIteratorIterator(
             new RecursiveArrayIterator($array),
             RecursiveIteratorIterator::LEAVES_ONLY
         ) as $value) {
    $vals[] = $value;
}
$max = max($vals);
echo $max;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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