我目前有一些代码从网站上获取一些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"
}
]
}
会很棒。我不知道该怎么做
答案 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) {
// ...
}