在PHP数组中查找最大值

时间:2016-03-24 07:11:06

标签: php arrays

下面是我的数组:

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

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

在这个数组中我想找到最大数字,如果数组包含相同的最大值,那么我们随机选择一个最大值。

预期输出如下:

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

        )

    [5] => Array
        (

            [4] => 3

        )

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

        )

)

这是我尝试过的:

$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>"

3 个答案:

答案 0 :(得分:3)

您将获得max()的最大值,但对于索引,您必须使用array_keys()

你可以试试这个:

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

答案 1 :(得分:3)

使用array_maparray_keys函数的简单解决方案:

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

输出:

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

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

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

答案 2 :(得分:0)

如果您只是想知道我理解的最高价值

  

在这个数组中我想找到最大数字和数组   包含相同的最大值,然后我们选择一个最大值   随机

你可以这样做

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

这将预先处理所有数组并推送$result上的值,然后您只需一个级别数组并轻松使用max函数