Reputation: 11
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"
}
}
}
]
Upvotes: 0
Views: 80
Reputation: 15141
Here i made few changes to your current code to make it work as expected.
foreach ($results as $result){
$data[$result['country']]=//added country as index.
array(
"name"=>$result['name'],
"id"=>$result['id'],
"Course"=>array(
array("hall1"=>$result['course1']),//surrounded it by array
array("hall2"=>$result['course2'])//surrounded it by array
)
);
}
echo json_encode($data,JSON_PRETTY_PRINT);
Upvotes: 1
Reputation: 416
Following snippet is just updated version of your code, the response which you want can be achieved by encoding JSON like this
json_encode($data,JSON_FORCE_OBJECT)
but it will make JSON Object only so your Course
Array will also become JSON OBJECT
foreach ($results as $result){
$arr[$result['country']] = [
'name' => $result['name'],
'id' => $result['id'],
'Course' => [
['hall1' => $result['course1']],
['hall2' => $result['course2']]
]
];
$data[] = $arr;
}
echo json_encode($data);
Upvotes: 0
Reputation: 6311
Make a array inside the array
"Course"=>array(
array("hall1"=>$result['course1']),
array("hall2"=>$result['course2']))
Upvotes: 0