我目前有一些代码,从一个网站抓取一些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成为更深层对象中的每个键。例如,$state->a直到位置7左右才会存在。当Deeper的计数为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"
}
]
}那就太好了。我不知道该怎么做
发布于 2011-05-25 00:10:12
在此之前
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) {
// ...
}https://stackoverflow.com/questions/6113183
复制相似问题