如何获取数组最小值

我有多维数组,我需要得到一个最小值。


数组可能是[65,4,4,511,5,[[54,54[.[.[..].].]]等等。


示例代码


<?php 


$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];

function NumMin($arr)

{

    $num = '';

    foreach ($arr as $item => $i) {

        if(is_array($i)){

            NumMin($i);

        }

        else{

                $num .= $i.',';


            }

    }



    $num .= $num;

    return $num;


}

$g = NumMin($arr);

var_dump($g);

我需要得到0


陪伴而非守候
浏览 99回答 2
2回答

收到一只叮咚

您可以使用array_walk_recursive()函数来展平给定的数组(使其成为一维)。然后使用简单min()的函数来获得所需的输出。array_walk_recursive($arr, function($v) use (&$res){&nbsp; &nbsp; $res[]=$v;&nbsp;});echo min($res);

慕标琳琳

<?php&nbsp;$GLOBALS["min"] = 999999; //min value int$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];array_walk_recursive($arr, 'NumMin');function NumMin($item){&nbsp; &nbsp; if(intval($item) <= intval($GLOBALS["min"]))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $GLOBALS["min"] = intval($item);&nbsp;&nbsp; &nbsp; }}// The end, $GLOBALS["min"] will have the least value回声 $GLOBALS["min"]; ?>
打开App,查看更多内容
随时随地看视频慕课网APP