我该如何处理可能具有对象或数组值的键?

时间:2011-05-24 15:50:48

标签: php json parsing

我目前有一些代码从网站上获取一些JSON。这基本上就是我目前所做的事情

$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;
}

现在只有一个'更深'时会出现问题。服务器将其作为JSON对象返回。 $ state然后成为Deeper对象中的每个键。 $ state-> a例如在7号位附近不会存在。当深度计数为1时,有没有办法可以将Deeper从JSON对象转换为数组?

希望这有助于说明我的问题:

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

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

将上面的内容转换为

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

会很棒。我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

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

你可能想要:

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.
}

<强>更新
如果您只想将$decoded_json->NewDataSet->Deeper放入数组中,那么:

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

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