Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

arrays - max() function can't find correct value. php

I'm trying to get the max value in the array. But using max() for the entire array it can't find the highest value:

enter image description here

The return Key is 2, which is not the correct key, obviously the highest value is in array(3). Please help me to find my mistake. Here bellow is my code:

<?php
$hex_splited = [
        ['00','00','00'], 
        ['10', '11', '10'], 
        ['F0', '1A', 'C3'],
        ['0F', 'FE', 'F4'],
       ];
$arr_rgb = [];
$count2 = count($hex_splited);
for ($i=0; $i < $count2; $i++) { 
    $inn_count = count($hex_splited[$i]);
    for ($j=0; $j < $inn_count; $j++) { 
            $val = hexdec($hex_splited[$i][$j]);
            $arr_rgb[$i][$j] = $val;
    }
}
$max = max($arr_rgb);
var_dump($max);
$key = array_search($max, $arr_rgb);
echo "<pre>";
echo "array key is: " . $key;
echo "</pre>";

    echo "<table border='1'>";
for ($m=0; $m < $count2; $m++) {
    echo "<tr>";
    for ($k=0; $k < $inn_count; $k++) { 
        echo "<td>";
        echo $arr_rgb[$m][$k];
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table>";
question from:https://stackoverflow.com/questions/65598483/max-function-cant-find-correct-value-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that max() doesn't always behave as you would expect when using multidimensional arrays.

This code does the processing in two stages, first finds the max value. As this is only a 2 dimensional simple array, you can use...

$max = max(array_map("max", $hex_splited));

This applies max to each of the sub arrays and then gets the max of those values.

So in your case, this will be 'FE'. Then as part of the loop which converts the data to decimal, it compares the original value with the max already found and stores the key...

$key = 0;
for ($i=0; $i < $count2; $i++) {
    $inn_count = count($hex_splited[$i]);
    for ($j=0; $j < $inn_count; $j++) {
        $val = hexdec($hex_splited[$i][$j]);
        $arr_rgb[$i][$j] = $val;
        // Check if found the max value
        if ( $max == $hex_splited[$i][$j] ) {
            $key = $i;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...