如何在不知道是否为数组的情况下遍历JSON属性? [英] how to iterate over JSON property not knowing if it's array or not?
问题描述
我有一个问题,其中API用DEPARTURESEGMENT响应我,有时只包含一个对象,有时又包含一个对象数组.视情况而定,我的foreach循环中似乎需要不同的逻辑.
I have this problem where an API responds to me with DEPARTURESEGMENT sometimes containing only one object, and sometimes containing an array of objects. Depending on which case it is, I seem to need different logics in my foreach-loop.
响应A:
{
"getdeparturesresult":{
"departuresegment":[{
"departure":{
"location":{
"@id":"7461018",
"@x":"12.523958",
"@y":"57.938402",
"name":"Noltorps centrum"
},
"datetime":"2014-12-04 23:05"
},
"direction":"Alingsås station",
"segmentid":{
"mot":{
"@displaytype":"B",
"@type":"BLT",
"#text":"Buss"
},
"carrier":{
"name":"Västtrafik",
"url":"http://www.vasttrafik.se/",
"id":"279",
"number":"1"
}
}
},
{
"departure":{
"location":{
"@id":"7461018",
"@x":"12.523958",
"@y":"57.938402",
"name":"Noltorps centrum"
},
"datetime":"2014-12-04 23:05"
},
"direction":"Alingsås station",
"segmentid":{
"mot":{
"@displaytype":"B",
"@type":"BLT",
"#text":"Buss"
},
"carrier":{
"name":"Västtrafik",
"url":"http://www.vasttrafik.se/",
"id":"279",
"number":"1"
}
}
}
]
}
}
使用此循环:
foreach ($apiData->getdeparturesresult->departuresegment as $m) {
此回复B:
{
"getdeparturesresult":{
"departuresegment":{
"departure":{
"location":{
"@id":"7461018",
"@x":"12.523958",
"@y":"57.938402",
"name":"Noltorps centrum"
},
"datetime":"2014-12-04 23:05"
},
"direction":"Alingsås station",
"segmentid":{
"mot":{
"@displaytype":"B",
"@type":"BLT",
"#text":"Buss"
},
"carrier":{
"name":"Västtrafik",
"url":"http://www.vasttrafik.se/",
"id":"279",
"number":"1"
}
}
}
}
}
需要这样的循环(否则会引发错误):
needs a loop like this (otherwise it throws an error):
foreach ($apiData->getdeparturesresult as $m) {
是否有一种方法可以编写循环故障保护,以判断DEPARTURESEGMENT是对象数组还是仅一个对象(方括号[]是json结构的唯一区别吗?)还是我必须以某种方式进行测试并首先查看DEPARTURESEGMENT是否为数组,并根据结果分配到两个不同的循环?
Is there a way to write the loop failsafe for whether DEPARTURESEGMENT is an array of objects or just one object (the brackets [] is the only difference to the structure of the json right?) or do I have to somehow test and see first whether DEPARTURESEGMENT is an array or not, and dispatch to two different loops depending on the outcome?
推荐答案
您有一些可以帮助您的方法:
You have a few methods that can help you:
- is_array
- is_object
- instanceof //如果收到特定对象
- gettype
- json_decode 第二个参数(如果设置为true)会尝试将json解码为数组
- is_array
- is_object
- instanceof // if you receive specific object
- gettype
- json_decode second parameter, which if is set to true, tries to decode the json as an array
在您的情况下,执行以下操作可能会很好:
In you situation, you would probably be fine by doing the following:
if (is_object($entry)) {
handleObject($entry);
} elseif (is_array($entry) && count($entry)) {
foreach ($entry as $e) {
handleObject($e);
}
}
这篇关于如何在不知道是否为数组的情况下遍历JSON属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!