How to convert multidimensional array into json object
15,111
Your desired output suggests it is an array of objects. Just loop over them and encode each subarray to json string, and decode it again to obtain an object:
foreach($array as $k =>$a){
$array[$k] = json_decode(json_encode($a));
}
If however you mean you want an array of json strings, omit the json_decode
:
foreach($array as $k =>$a){
$array[$k] = json_encode($a);
}
Author by
codex
Updated on June 07, 2022Comments
-
codex almost 2 years
i have an issue in array to json conversion, I have an array and i want to convert this array into json objects, desired output given below so any one please help me.
Php array
Array ( [0] => Array ( [application_id] => 132 [application_status] => SUBMITTED [reference_number] => [salutation] => [first_name] => [middle_name] => [last_name] => [mother_name] => ) [1] => Array ( [application_id] => 148 [application_status] => SUBMITTED [reference_number] => [salutation] => [first_name] => [middle_name] => [last_name] => [mother_name] => ) [2] => Array ( [application_id] => 154 [application_status] => SUBMITTED [reference_number] => [salutation] => [first_name] => [middle_name] => [last_name] => [mother_name] => ) [3] => Array ( [application_id] => 182 [application_status] => SUBMITTED [reference_number] => [salutation] => [first_name] => [middle_name] => [last_name] => [mother_name] => ) [4] => Array ( [application_id] => 186 [application_status] => SUBMITTED [reference_number] => [salutation] => [first_name] => [middle_name] => [last_name] => [mother_name] => ) )
Convert above array to json object like this:
[ { "application_id": "1", "application_status": "0", "reference_number": "/index", "salutation": "index", "first_name": "Index", "middle_name": "Home", "last_name": "1", }, { "application_id": "1", "application_status": "0", "reference_number": "/index", "salutation": "index", "first_name": "Index", "middle_name": "Home", "last_name": "1", }, { "application_id": "1", "application_status": "0", "reference_number": "/index", "salutation": "index", "first_name": "Index", "middle_name": "Home", "last_name": "1", }, { "application_id": "1", "application_status": "0", "reference_number": "/index", "salutation": "index", "first_name": "Index", "middle_name": "Home", "last_name": "1", }, { "application_id": "1", "application_status": "0", "reference_number": "/index", "salutation": "index", "first_name": "Index", "middle_name": "Home", "last_name": "1", }, ]