0

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"
},

}

2 Answers 2

4

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"
    }
]
0
1

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 {}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.