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

后端 未结 4 1550
眼角桃花
眼角桃花 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:54

    You could use iterators to make your function a whole lot easier:

    function findSourceChannel($array)
    {
        foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
            if ($key == 'sourceChannel') {
                return $value['id'];
            }
        }
        return null;
    }
    

    That said, I'm not sure why you can't just do a search like this:

    foreach ($array['results'] as $result) {
        if (isset($result['sourceChannel'])) {
            return $result['sourceChannel']['id'];
        }
    }
    return null;
    

提交回复
热议问题