I am building an array (json encoded) and returning it to the caller. My output currently looks like this:
JavaScript
x
[{"org_id":1,"org_name":"Org 1"},{"org_id":4,"org_name":"Org 4"}]
I want to add a name so that output looks like this:
JavaScript
{
“orgs” : [
{"org_id":1,"org_name":"Org 1"},
{"org_id":4,"org_name":"Org 4"}
]
}
Here is my current code:
JavaScript
// if orgs were found then
if ( is_array($orgs) && !empty($orgs) ) {
$json_orgs = json_encode($user_orgs);
// else return an empty array
} else {
$user_orgs = array();
}
I am fairly new to OO coding, so I have not figured out how to initialize an object so that “orgs” is present. Maybe I don’t even need an object. Any help would be greatly appreciated.
Advertisement
Answer
Before you json encode the array, just wrap it in another one:
JavaScript
$newArray = ['orgs' => $yourCurrentArray];
Then you json encode the new variable instead.
If you rather not create a new array, you can simply do:
JavaScript
json_encode(['orgs' => $yourCurrentArray]);
This doesn’t really have anything to do with OOP since you’re just working with arrays. Associative arrays becomes objects when encoded into JSON.