我有一個數組,並希望將一些靜態值添加到數組中,並獲得JSON中的預期結果。PHP的Mysql結果到JSON
原始數組:
$results=
array (
0 =>
array (
'country' => 'SG ',
'id' => '1 ',
'name' => 'jerome ',
'course1' => 'IT ',
'course2' => 'Music ',
),
1 =>
array (
'country' => 'US ',
'id' => '2 ',
'name' => 'cindy ',
'course1' => 'IT ',
'course2' => 'Music ',
),
);
預期JSON結果:
{
"SG":{
"name":"jerome",
"id":"1",
"Course":[
{
"hall1":"IT"
},
{
"hall2":"Music"
}
]
},
"US":{
"name":"cindy",
"id":"2",
"Course":[
{
"hall1":"IT"
},
{
"hall2":"Music"
}
]
}
}
我試圖用這個來呼應數組轉換成JSON,但未能得到預期的結果
foreach ($results as $result){
$data[]=array(
$result['country']=>array(
"name"=>$result['name'],
"id"=>$result['id'],
"Course"=>array(
"hall1"=>$result['course1'],
"hall2"=>$result['course2']
)
)
);
}
echo json_encode($data);
結果:
[
{
"SG":{
"name":"jerome",
"id":"1",
"Course":{
"hall1":"IT",
"hall2":"Music"
}
}
},
{
"US":{
"name":"cindy",
"id":"2",
"Course":{
"hall1":"IT",
"hall2":"Music"
}
}
}
]
看看這個https:// stackov erum.com/questions/4064444/returning-json-from-a-php-script(我無法評論) – Richard