Why doesn't this PHP recursive function return the value?

后端 未结 4 1566
眼角桃花
眼角桃花 2020-12-12 02:03


I was working on an API for ustream which returns the following array

Array
(
[results] => Array
    (
        [0] => Array
            (
                 


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 02:39

    You're not doing anything with the return from your recursion call. It's a bit more complex than simply returning it, because you only want to cascade out if we actually found anything.

    Try this:

    function recursion($array) {
        foreach ($array as $key => $value) {
            if($key==='sourceChannel') {
                return $value['id'];
            }
            if (is_array($value)) {
                $rc = recursion($value);
                if (!is_null($rc)) return $rc;
            }
        }
        return null;
    }
    

    First, I added return null; to the end of the function - if we didn't find anything, we return null.

    Then, when I recurse, I check the return value... if it's non-null, it means we found something and we want to return it. If it is null, we don't want to return - we want to continue the loop instead.

提交回复
热议问题