简体   繁体   中英

How to get key of the biggest element in 2d array in PHP

Example array

$array[0][0] = 5323;
$array[0][1] = 5346;
$array[0][2] = 5424;
$array[1][0] = 6000;
$array[1][1] = 5412;
$array[1][2] = 5543;
$array[2][0] = 5651;
$array[2][1] = 7000;
$array[2][2] = 5254;

So biggest element in this array has value 7000; How to get his keys X and Y? (as in $array[X][Y], so in this case that would be x = 2 and y = 1);

You can just loop through the array and save the xy when you get a new maximum value.

I start max with the minimum number possible and from there it loops the array and updates the variables if the value is larger than the previous max.

$max = PHP_INT_MIN;

foreach($array as $key => $subarray){
    foreach($subarray as $subkey => $value){
        if($value > $max){
            $x = $key;
            $y = $subkey;
            $max = $value;
        }
    }
}

https://3v4l.org/5hHXP

One approach could be to make a string of your current array, and then create an array of all values in the string and fetch max value by using PHP's native function max on the array:

$na = '';
foreach($array as $arr) {
    $na .= implode(',',$arr) . ',';
}
$max_value = max(explode(',',$na));

foreach($array as $x=>$arr) {
    $y = array_search($max_value, $arr);    
    if ($y !== false) break;
}

Then you would have your values in $x, $y and $max_value

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