Skip to content
Advertisement

How do I build an object array such that I get a properly formatted JSON output to match what is required?

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:

JavaScript

Instead I am getting the following:

JavaScript

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:

JavaScript

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):

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement