好吧,我已經在最後24小時內敲了敲頭,在測試和讀取SO之後無法弄清楚這一點。我有一個JSON文件,我需要解析,出於某種原因,我無法得到正確的代碼組合來回應除「數組」或「嘗試獲取非對象的屬性」或「爲foreach提供的無效參數以外的任何內容)」。這裏是我試圖迭代的完整JSON。我需要輸出每個「項目」的名稱,每個項目中的「數據集」以及每個「數據集」的「權限」。我自己構建這個JSON,所以我可以根據需要更改格式。使用PHP解析和回顯JSON
$data = json_decode($json, true);
輸出JSON如下:
[
[
{
"projects":[
{
"project":"test-project-1",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"OWNER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"WRITER",
"google_group":"[email protected]"
}
]
}
]
},
{
"project":"test-project-2",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
}
]
}
]
}
]
]
我已經試過了諸如:
foreach($data->projects as $output)
{
echo $output->project . "\n";
foreach($output->datasets as $datasets)
{
echo $output->dataset . "\n";
}
}
感謝您的幫助!
編輯:工作代碼解析JSON以上:
$projects = $json['projects'];
foreach ($projects as $project) {
echo $project['project'] . "<br>";
foreach ($json['projects'][0]['datasets'] as $datasets){
echo $datasets['dataset'] . "<br>";
foreach ($json['projects'][0]['datasets'][0]['permissions'] as $permissions){
echo $permissions['role'] . "<br>";
echo $permissions['google_group'] . "<br>";
}
}
}
'的var_dump($輸出 - >數據集);' – mkaatman