I need to produce a json formatted array. My query returns an array for org ids and names. I need the format of the output to be as seen below:
"orgs": [ { "org_id":"1", "org_name":"ABC" }, { "org_id":"2", "name":"DEF" }, { "org_id":"3", "name":"GHI" } ]
Instead I am getting the following:
{"0":{"org_id":1,"org_name":"ABC"},"1":{"org_id":2,"org_name":"DEF"}}
I am fairly new to OO coding within PHP, so I am not sure how to properly load my array to then be JSON encoded. I have tried the following, but am not quite getting the right result:
$orgs = get_orgs(); $userorgs = array(); if ( is_array($orgs) && !empty($orgs) ) { foreach ($orgs as $key => $value) { if ( !empty($value['short_name']) ) { $userorgs[] = (object) ['org_id' => $value['org_id'], 'org_name' => $value['short_name']]; } else { $userorgs[] = (object) ['org_id' => $value['org_id'], 'org_name' => $value['long_name']]; } } } $json_orgs = json_encode($userorgs, JSON_FORCE_OBJECT); echo $json_orgs;
Any help would be greatly appreciated.
Advertisement
Answer
Your method of loading data is fine. You need to remove the JSON_FORCE_OBJECT
flag from your call to json_encode
. json_encode
will automatically generate objects for associative arrays, but with that flag it will also turn numerically indexed arrays into objects.
For example (based on your data):
$arr = array ( 0 => array ( 'org_id' => 1, 'org_name' => 'ABC', ), 1 => array ( 'org_id' => 2, 'org_name' => 'DEF', ), ); echo json_encode($arr, JSON_PRETTY_PRINT) . "n"; echo json_encode($arr, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
Output:
[ { "org_id": 1, "org_name": "ABC" }, { "org_id": 2, "org_name": "DEF" } ] { "0": { "org_id": 1, "org_name": "ABC" }, "1": { "org_id": 2, "org_name": "DEF" } }