如何在多维数组中找到最大值?

编程入门 行业动态 更新时间:2024-10-11 01:19:29
本文介绍了如何在多维数组中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下数组:

$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

更多推荐

如何在多维数组中找到最大值?

本文发布于:2023-11-29 08:54:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645928.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   最大值   数组   中找到   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!