PHP - using a recursive function to find the max() of nested arrays

后端 未结 2 1592
北海茫月
北海茫月 2021-01-25 17:11

The following code uses a simple strategy for finding the max of the nested array. It uses foreach to find and label the max value, however, if I got an array that was nested t

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-25 17:53

    What you want is a recursive function.

    The function looks up the biggest element in a an array. If an item in the array is an array, it will find the biggest item in that array and use that to compare.

    To find the biggest value in that array it will use the same function.

    function findMax($arr){
        $max = 0;
        foreach($arr as $item){
            if(is_array($item)){
                $val = findMax($item);
            }else{
                $val = $item;
            }
            $max  = $val>$max?$val:$max;
        }
        return $max;
     }
    

    Use example:

    $arr = Array(1,2,Array(3,10,Array(6,7)));
    $arr2 = Array(1,2,Array(3,5,Array(6,7)));
    echo findMax($arr)."\n".findMax($arr2);
    

    Result:
    10
    7

提交回复
热议问题