开发者

How should I handle a key that could have an object or array value?

I currently have some code which grabs some JSON from a site. This is basically what I currently do

$valueObject = array();
if (isset($decoded_json->NewDataSet)) {
             foreach ($decoded_json->NewDataSet->Deeper as $state) {
                 $i = count($valueObject);
                 $valueObject[$i] = new ValueObject();
                 $valueObject[$i]->a = $state->a;
}

Now the problem occurs when there is only one 'Deeper'. The server returns it as a JSON object. $state then becomes each key in the Deeper object. $state->a won't exist until around position 7 for example. Is there any way I could convert Deeper from a JSON object to array when the count of deeper is one?

Hopefully this helps illustrate my problem:

"NewDataSet": {
        "Deeper": [
            {
                "a": "112",
                "b": "1841"
            },
            {
                "a": "111",
                "b": "1141"
            }
        ]
    }
}

versus

"NewDataSet": {
        "Deeper":
            {
                "开发者_如何学Ca": "51",
                "b": "12"
            }
}

converting above to

"NewDataSet": {
      "Deeper": [
           {
               "a": "51",
               "b": "12"
           }
       ]
}

would be great. I don't know how to do this


Before

foreach ($decoded_json->NewDataSet->Deeper as $state)

you probably want to:

if (is_array($decoded_json->NewDataSet)) {
    // This is when Deeper is a JSON array.
    foreach ($decoded_json->NewDataSet->Deeper as $state) {
        // ...
    }
} else {
    // This is when Deeper is a JSON object.
}

Update
If you just want to make $decoded_json->NewDataSet->Deeper into an array, then:

if (!is_array($decoded_json->NewDataSet->Deeper)) {
    $decoded_json->NewDataSet->Deeper = array($decoded_json->NewDataSet->Deeper);
}

foreach ($decoded_json->NewDataSet->Deeper as $state) {
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜