我的第一个递归函数没有正确调用本身呢? [英] My first recursive function not calling itself correctly?
本文介绍了我的第一个递归函数没有正确调用本身呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这件code的应该是找到一组,价值最高无论有多少嵌套数组有。我想,对于首次创建将每一个事件发生时调用自身,这就是价值是一个数组的函数。为什么说我的变量没有定义?
< PHP
$ ARR =阵列(1,2,阵列(3,4)); 功能getitMax($ ARR){
的foreach($改编为$值){
如果(is_array($值)){
getitMax($值);
}其他{
$ max_array =阵列($值);
}
}
}
getitMax($ ARR); 回声MAX($ max_array);
?>
解决方案
您的问题是,你只是调用你在这里的功能:
如果(is_array($值)){
getitMax($值);}
- 但什么都不做与它的结果。而且你的函数没有收益
- 即结果将是空
。为了解决这个问题,这样做:
函数getitMax($ ARR)
{
$最大= NULL;
的foreach($改编为$值)
{
如果(is_array($值))
{
$电流= getitMax($值);
}
其他
{
$目前= $价值;
}
//分配的最大电流,如果电流较大:
如果($当前> $最大值)
{
$最大= $电流;
}
}
返回$最大;
}
This piece of code is supposed to find the highest value of a group, no matter how many nested arrays there are. I am trying, for the first time, to create a function that will call itself every time the event happens, that's the value is an array. Why is it saying my variables are not defined?
<?php
$arr = array("1", "2", array("3", "4"));
function getitMax($arr){
foreach ($arr as $value){
if(is_array($value)){
getitMax($value);
} else {
$max_array=array($value);
}
}
}
getitMax($arr);
echo max($max_array);
?>
解决方案
Your problem is that you're just calling your function here:
if(is_array($value)){
getitMax($value);
}
-but doing nothing with it's result. And also your function has no return
- i.e. result will be null
. To fix this, do something like:
function getitMax($arr)
{
$max = null;
foreach($arr as $value)
{
if(is_array($value))
{
$current = getitMax($value);
}
else
{
$current = $value;
}
//assign max to current if current is larger:
if($current>$max)
{
$max = $current;
}
}
return $max;
}
这篇关于我的第一个递归函数没有正确调用本身呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文