I have one array and would like to add some static value into array and get the expected result in JSON.
Original Array:
$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 ',
),
);
Expected JSON Result:
{
"SG":{
"name":"jerome",
"id":"1",
"Course":[
{
"hall1":"IT"
},
{
"hall2":"Music"
}
]
},
"US":{
"name":"cindy",
"id":"2",
"Course":[
{
"hall1":"IT"
},
{
"hall2":"Music"
}
]
}
}
I tried to use this to echo array into json but failed to get the expected result
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);
Result:
[
{
"SG":{
"name":"jerome",
"id":"1",
"Course":{
"hall1":"IT",
"hall2":"Music"
}
}
},
{
"US":{
"name":"cindy",
"id":"2",
"Course":{
"hall1":"IT",
"hall2":"Music"
}
}
}
]