Reputation: 73
Here my simple code..
$country=['Bangladesh','Pakistan'];
$capital=['Dhaka','Islamabad'];
return response()->json([
'country'=>$country,
'roll'=>$roll,
]);
If i run the above code ,the output will be like below..
{
"country": [
"Bangladesh",
"Pakistan"
],
"roll": [
'Dhaka',
'Islamabad'
]
}
But I want that my expected output will be like .. EDIT: Following JSON is invalid (2 same key country)
{
{
"country":"Bangladesh",
"capital":"Dhaka"
},
{
"country":"Pakistan",
"capital":"Islamabad"
},
}
Upvotes: 0
Views: 201
Reputation: 12391
try this
$countries = ['India', 'Bangladesh', 'Pakistan'];
$capital = ['Delhi', 'Dhaka', 'Islamabad'];
$response = [];
foreach ($countries as $key => $country) {
$response[$key] = [
'country' => $country,
'capital' => $capital[$key],
];
}
return response()->json($response);
it will return
[{
"country": "India",
"capital": "Delhi"
},
{
"country": "Bangladesh",
"capital": "Dhaka"
},
{
"country": "Pakistan",
"capital": "Islamabad"
}
]
Upvotes: 4
Reputation: 1351
Your expected output is wrong. You simply cant have 2 same keys (country
) in output json. You should have country and capital encapsulated in separate {}.
Upvotes: 1