我是PHP新手并尝试生成以下json输出:
{
"contacts": [
{
"id": "1",
"name": "John Bob",
"email": "john@bob.com"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "johnny@mac.com"
},
.....
]
}
我有以下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": "john@bob.com"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "johnny@mac.com"
},
]
我阅读this tutorial并将$final[]
更改为$final['contacts']
,但仍然无法生成所需的json文件。
答案 0 :(得分:0)
foreach ($contacts as $contact)
{
.....
$final['contacts'][] = array(
array( //insert all your array in contacts
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
答案 1 :(得分:0)
或者:
$final['contacts'][] = array(..);
或:
$contacts_output = array();
foreach ($contacts as $contact) {
$contacts_output[] = array(..);
}
$final = array('contacts' => $contacts_output);
echo json_encode($final, JSON_PRETTY_PRINT);
答案 2 :(得分:0)
试试这个:
$final = array();
$final['contacts'] = array();
foreach ($contacts as $contact)
{
.........
$final['contacts'][] = array(
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
答案 3 :(得分:0)
$final = array('contacts'=>[]);
foreach ($contacts as $contact)
{
$final['contacts'] []=
array( //insert all your array in contacts
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}