我在这个json数据上使用json_decode:
issues": [
{
"id": "51526",
"key": "123",
"fields": {
"zone": [
{
"name": "football",
"active": true
},
{
"name": "baseball",
"active": true
}
],
"icon": {
"id": "1"
}
}
},
{
"id": "51228",
"key": "3108",
"fields": {
"zone": null,
"icon": {
"id": "10"
}
}
}
]
}
我可以正确提取名称数据,这将是[“足球”,“棒球”]。但是,我还想从第二个数据集中捕获空值,这样我的数据看起来就像
["football", "baseball", null].
基本上,我想查看“zone”并获取“name”的值,如果“zone”为null,则值为null以获取此数据结构[“football”,“baseball”,null ]
我已经尝试了所有我能想到的东西,但我对PHP并不擅长。这可能吗?
Php代码:
$decoded_array = json_decode($result)->{'issues'};
foreach($decoded_array as $issues){
foreach($issues->{'fields'}->{'zone'} as $zn){
$nm[] = $zn->{'name'};
}
}
答案 0 :(得分:1)
您可以这样做:
$data = json_decode($json);
$issues = $data->issues;
$names = array();
foreach($issues as $issue){
$zones = $issue->fields->zone;
foreach($zones as $zone){
if($zone != null){
$name = $zone->name;
array_push($names,$name);
}else{
array_push($names,null);
}
}
}
答案 1 :(得分:0)
当你迭代json对象时,检查" zone"一片空白。如果是,则可以在结果数组中添加null。
伪代码:
Iterate jsonObject if (jsonObject["fields"]["zone"] == null) then push_in_array(result,null)