如何在多维数组中找到最大值? [英] How to find the highest value in a multidimensional array?

查看:162
本文介绍了如何在多维数组中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

$ar3 = array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676);

我需要借助递归比较所有元素,以找到最大值.

I need to compare all of its elements with the help of recursion to find the maximum value.

我设法在最深的数组中找到最大值:

I've managed to find the highest value in the deepest array:

$ar3 = array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676); 

function arr_max_rec($ar3)
{
    $max = $ar3[0];
    foreach ($ar3 as $key => $value){
        if ($max < $ar3[$key] and !is_array($value)){
            $max = $ar3[$key];
        }
        elseif (is_array($ar3[$key])){
            return arr_max_rec($ar3[$key]);
        }
    }return $max;
}
echo arr_max_rec($ar3);

但是我需要比较所有数字并找到最高的数字.数组的深度可以是任意的.

But I need to compare all the numbers and find the highest one. The depth of the array can be any.

推荐答案

您可以尝试使用递归函数

You can try using recursive function

    <?php

    $ar3=array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676); 

    function highestValue($ar3) {
       foreach($ar3 as $key => $value) {
           if (is_array($value)) {
               $ar3[$key] = highestValue($value);
           }
       }

         return max($ar3);
    }

    echo highestValue($ar3); //1155

这篇关于如何在多维数组中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆