doutang6600 2012-03-08 14:46
浏览 54
已采纳

递归函数: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...

  • 写回答

2条回答 默认 最新

  • duanhui4160 2012-03-09 10:28
    关注

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

    So, no return anymore...

    $_SESSION['item'][$target] = $_SESSION['group'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?