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

后端 未结 4 1565
眼角桃花
眼角桃花 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 03:04

    Your code is flawed because you need to change

    recursion($value);
    

    into

    return recursion($value);
    

    The return will take the answer back to the caller until the first caller is reached.

    edit: The lesson here is that your function should ALWAYS return a value. So here is some more elaboration:

    function recursion($array) {
        if (!is_array($array)) // check if what you're getting is an array!
            return null;
        foreach ($array as $key => $value) {
            if($key==='sourceChannel') {
                return $value['id'];
            }
            if (is_array($value)) {
                $result = recursion($value);
                if ($result !== null) {
                    return $result;
                }
            }
        }
        return null; // this happens if all recursions are done and sourceChannel was not found
    }
    

提交回复
热议问题