Skip to content
Advertisement

PHP – How do I add a name to an array

I am building an array (json encoded) and returning it to the caller. My output currently looks like this:

[{"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:

{
  “orgs” : [
    {"org_id":1,"org_name":"Org 1"},
    {"org_id":4,"org_name":"Org 4"}
  ]
}

Here is my current code:

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

$newArray = ['orgs' => $yourCurrentArray];

Then you json encode the new variable instead.

If you rather not create a new array, you can simply do:

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.

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