jonmrich
jonmrich

Reputation: 4323

Properly adding array to array in PHP

I'm trying to put an array inside an array (inside an array) using PHP.

$objectArray = array ('id' => $place, 'name'=>$placeName, array ('contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)));
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;

This gives me something like this:

{
"place": {
    "0": {
        "contact_info": {
            "phone": "513-555-1212",
            "email": "[email protected]",
            "website": "https://example.com"
        }
    },
    "id": "999999",
    "name": "My House",
 }
}

What I'm looking for as an end product is:

{
"place": {
    "contact_info": {
        "phone": "513-555-1212",
        "email": "[email protected]",
        "website": "https://example.com"
        },
    "id": "999999",
    "name": "My House",
 }

I need to not have the '0' and the contact info part under place

Upvotes: 0

Views: 22

Answers (2)

zenwraight
zenwraight

Reputation: 2000

You need something like this

$objectArray = array (
   'id' => '99999', 
   'name'=>'My House', 
   'contact_info' => array (
       'phone'=>'513-555-1212',
       'email'=>'[email protected]',
       'website'=>'https://example.com'
   )
);
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;

Remove the array part placed before 'contact_info' so they come at same level.

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

For your purposes $objectArray should have this structure:

$objectArray = array ( 
    'id' => $place, 
    'name'=>$placeName, 
    'contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)
);

So, contact_info should be on the same level as id and name, without new array.

Upvotes: 2

Related Questions