简体   繁体   中英

php foreach Iteration through json

Assume that I have below json response fetched from an API.

{
    "owner": "Jane Doe",
    "pets": [
        {
            "color": "white",
            "type": "cat"
        },
        {
            "color": "black",
            "type": "dog"
        }
    ]
}

From the below PHP code I have converted the json string into a json object. And displayed the pet types.

$jsonObject = json_decode($json);

foreach($jsonObject->pets as $pets){
    echo 'Pet type:'.$pets->type.'</br>';
}

However in some cases the response json from the API is in below format

{
    "owner": "John Doe",
    "pets": {
        "color": "white",
        "type": "cat"
    }
}

in this case above php foreach iteration fails with below message

*Notice: Trying to get property of non-object *

I'm looking for a easy way to do this because the actual json response which i'm handling has lot of these occurrences.

You need to check whether $jsonObject->pets is an array or object. If it's an object, replace it with an array containing that object, then the loop will work.

if (!is_array($jsonObject->pets)) {
    $jsonObject->pets = array($jsonObject->pets);
}

You could also do it with a conditional in the foreach :

foreach (is_array($jsonObject->pets) ? $jsonObject->pets : [jsonObject->pets] as $pet) {
    ...
}

If you don't want to have to write all that every time, you could put it in a function:

function as_array($x) {
    return is_array($x) ? $x : [x];
}

and then use:

foreach (as_array($jsonObject->pets) as $pet) {
    ...
}

I'd also complain to the API designer. It's ridiculous to return inconsistent data formats like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM