递归函数:echo工作,返回不工作

递归函数:echo工作,返回不工作

问题描述:

The function aims at finding an item in a range of arrays, and then returning its key.

Problem is that the function doesn't return anything, whereas it would echo the expected result... Here is my code:

function listArray($tb, $target){
    foreach($tb as $key => $value){
        if(is_array($value)){ // current value is an array to explore
            $_SESSION['group'] = $key; // saving the key in case this array contains the searched item
            listArray($value, $target);
        }else {
            if ($target == $value) { // current value is the matching item
                return $_SESSION['group']; //Trying to return its key
                break; // I'd like to close foreach as I don't need it anymore
                }
        }
    }
}

By the way, an other little thing: I'm not used to recursive function, and I didn't find any other solution than using a session variable. But there might be a nicer way of doing it, as I don't use this session variable elsewhere...

该函数旨在查找一系列数组中的项目,然后返回其键。 p> \ n

问题是该函数没有返回任何内容,而它会回显预期的结果...... 这是我的代码: p>

  function listArray(  $ tb,$ target){
 foreach($ tb as $ key => $ value){
 if(is_array($ value)){//当前值是要探索的数组
 $ _SESSION ['group  '] = $ key;  //保存密钥,以防此数组包含搜索项
 listArray($ value,$ target); 
} else {
 if($ target == $ value){//当前值是匹配项\  n返回$ _SESSION ['group'];  //试图返回其键
 break;  //我想关闭foreach,因为我不再需要了它
} 
} 
} 
} 
  code>  pre> 
 
 

顺便说一下, 另一件小事:我不习惯递归函数,除了使用会话变量之外我没有找到任何其他解决方案。 但是可能有更好的方法,因为我不在其他地方使用这个会话变量...... p> div>

I finally bypassed the problem by storing my result in a $_SESSION variable.

So, no return anymore...

$_SESSION['item'][$target] = $_SESSION['group'];

You need a return before the recurring listArray call.

Thank about it ..

return;
break;

That break is never reached (I don't believe you can use break to exit a function in php anyway)

The second return returns from a recursive call. Let's say that this was not two separate functions:

function foon() {
   barn();
}
function barn() {
   return true;
}

foon has no return statement.