0

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

1
  • 1
    eliminate the cast array('contact_info' ..) and let it just contact_info => Commented May 11, 2017 at 14:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Notice how writing the code using this format (instead of oneliner) helps seeing this kind of problems easier.
Thanks! This worked! @AlvaroFlañoLarrondo Great point...something to keep in mind. Thanks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.