简体   繁体   中英

Find maximum value in PHP array

Below is my array:

Array
(
    [3] => Array
        (
            [2] => 3
            [4] => 1
            [5] => 2
            [6] => 2
        )

    [5] => Array
        (
            [2] => 1
            [3] => 2
            [4] => 3
            [6] => 3
        )

In this array I want to find the maximum number and if the array contains the same maximum values then we choose one maximum value randomly.

Expected output like below:

Array
(
    [3] => Array
        (
            [2] => 3

        )

    [5] => Array
        (

            [4] => 3

        )

    [6] => Array
        (
            [2] => 3

        )

)

This is what I've tried:

$found = Array( [3] => Array ( [2] => 3 [4] => 1 [5] => 2 [6] => 2 ) [5] => Array ( [2] => 1 [3] => 2 [4] => 3 [6] => 3 ) [6] => Array ( [2] => 3 [3] => 2 [4] => 2 [5] => 3 )) 
$fmaxnum = array(); 

foreach($found as $fk => $fv){ 
   $fmaxnum[$fk] = max($fv); 
} 
echo "<pre>";print_r($fmaxnum);echo "</pre>"

You will get max value with max() but for index you have to use array_keys()

You can try this:

$found = Array ( '3' => Array ( '2' => 3 ,'4' => 1, '5' => 2, '6' => 2 ),
                 '5' => Array ( '2' => 1 ,'3' => 2, '4' => 3, '6' => 3 ),
                 '6' => Array ( '2' => 3 ,'3' => 2, '4' => 2, '5' => 3 )
                );
$fmaxnum = array(); 
foreach($found as $fk => $fv){ 
    $max_key = array_keys($fv, max($fv));
    $fmaxnum[$fk] = array(
      ($max_key[0]) => max($fv) /* This will give small index value */  
      /* (count($max_key)-1) => => max($fv) // this will give highest index value */
    );
} 

echo "<pre>";
print_r($fmaxnum);
echo "</pre>";

Simple solution with array_map and array_keys functions:

// supposing $arr is your initial array
$arrMax = array_map(function($v){
    $maximum = max($v);
    return  [array_keys($v, $maximum)[0] => $maximum];
}, $arr);

print_r($arrMax);

The output:

Array
(
    [3] => Array
        (
            [2] => 3
        )

    [5] => Array
        (
            [4] => 3
        )

    [6] => Array
        (
            [2] => 3
        )
)

if you just want to know the highest value as I understood

In this array I want to find the maximum number and if the array contains the same maximum values then we choose one maximum value randomly.

you could just do this

$array = [['3','1','2','2'],['1','2','3','3'],['2','1','1','3']]; 
$result = []; 

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
    $result[] = $value;
}

echo max($result);  

this will foreach all the array and push the values on $result , then you just have one level array and easily use max function

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