PHP - 使用递归函数查找嵌套数组的最大() [英] PHP - using a recursive function to find the max() of nested arrays

查看:260
本文介绍了PHP - 使用递归函数查找嵌套数组的最大()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code使用查找嵌套数组的最大一个简单的策略。它使用的foreach,查找并标注最大值,但如果我被嵌套到两个以上的水平,比我的code是无用的数组。任何人都可以请向我解释自称为它找到无限的嵌套数组函数的想法?将非常AP preciated。

下面是我的code,例如:

 < PHP
$ ARR =阵列(1,2,阵列(3,4));
的foreach($改编为$值){
     如果(is_array($值)){
             的foreach($值$值2){
                     $ max_array =阵列($值);
                     //没有更深层次             }
     }其他{
       $ max_array =阵列($值);
     }
}
回声MAX($ max_array);
?>


解决方案

您可以使用 array_walk_recursive() 吧:

 函数array_max_recursive($ ARR)
{
    $最大= -​​INF;    array_walk_recursive($ ARR,功能($项目)使用(安培; $最大值){
        如果($项目> $最大){
            $最大= $项目;
        }
    });    返回$最大;
}回声array_max_recursive([1,2,[3,4]]); // 4

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 to MORE than two levels, than my code would be useless. Can anyone please explain to me the idea of a function calling itself for it to find unlimited nested arrays? Would be much appreciated.

Here is my code for example:

<?php
$arr = array("1", "2", array("3", "4"));
foreach($arr as $value){
     if(is_array($value)){
             foreach($value as $value2){
                     $max_array=array($value);
                     // no deeper levels

             }
     } else {
       $max_array=array($value);
     }
}
echo max($max_array);
?>

解决方案

You can use array_walk_recursive() for it:

function array_max_recursive($arr)
{
    $max = -INF;

    array_walk_recursive($arr, function($item) use (&$max) {
        if ($item > $max) {
            $max = $item;
        }
    });

    return $max;
}

echo array_max_recursive(["1", "2", ["3", "4"]]); // 4

这篇关于PHP - 使用递归函数查找嵌套数组的最大()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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