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

后端 未结 3 419
既然无缘
既然无缘 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 20:51

    How about checking whether it's an array or not with is_array? I made a simple example of it's usage here - http://codepad.org/WNjbIPZF

    0 讨论(0)
  • 2021-01-25 20:56

    You have a few methods that can help you:

    • is_array
    • is_object
    • instanceof // if you receive specific object
    • gettype
    • json_decode second parameter, which if is set to true, tries to decode the json as an array

    In you situation, you would probably be fine by doing the following:

    if (is_object($entry)) {
        handleObject($entry);
    } elseif (is_array($entry) && count($entry)) {
        foreach ($entry as $e) {
            handleObject($e);
        }
    }
    
    0 讨论(0)
  • 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)
        ...
    
    0 讨论(0)
提交回复
热议问题