我是新來的PHP,並試圖產生以下JSON輸出:Array對象的PHP
{
"contacts": [
{
"id": "1",
"name": "John Bob",
"email": "[email protected]"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "[email protected]"
},
.....
]
}
,我有下面的PHP代碼:
$final = array();
foreach ($contacts as $contact)
{
.....
$final[] = array(
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($final, JSON_PRETTY_PRINT);
然而
,此輸出:
[
{
"id": "1",
"name": "John Bob",
"email": "[email protected]"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "[email protected]"
},
]
我讀了this tutorial,改變$final[]
到$final['contacts']
但ST生病無法產生所需的json文件。
謝謝第一種方法解決了這個問題。你能解釋爲什麼嗎? – semangi
因爲它增加了一個你需要的更多密鑰和數組的額外等級......! – deceze