how to iterate over JSON property not knowing if it's array or not?

后端 未结 3 418
既然无缘
既然无缘 2021-01-25 20:28

I have this problem where an API responds to me with DEPARTURESEGMENT sometimes containing only one object, and sometimes containing an array of objects. Depending on which case

3条回答
  •  清歌不尽
    2021-01-25 21:15

    I have this little useful function in my standard repertoire:

    function iter($x) {
        if(is_array($x))
            return $x;
        if(is_object($x)) {
            if($x instanceof \Iterator)
                return $x;
            if(method_exists($x, 'getIterator'))
                return $x->getIterator();
            return get_object_vars($x);
        }
        return array($x);
    }
    

    This way you can use any variable with foreach without having to check it beforehand:

     foreach(iter($whatever) as $item)
        ...
    

提交回复
热议问题