1

This is my code:

$amenitiesObject = array('parameter-amenities' => array('value' =>  $amenities));
$buildingObject = array('parameter-building' => array('value' =>  $building));

$data = array($amenitiesObject, $buildingObject);
$post_data = json_encode($data, JSON_FORCE_OBJECT);
return $post_data;

the result is:

{"0":{"parameter-amenities":{"value":""}},"1":{"parameter-building":{"value":""}}}

while i was hoping for this:

{"parameter-amenities":{"value":""},"parameter-building":{"value":""}}

what is my mistake please?

2
  • 1
    $data = array_merge( $amenitiesObject, $buildingObject ); Commented Apr 5, 2016 at 0:40
  • @fusion3k yes works, thanks Commented Apr 5, 2016 at 0:42

1 Answer 1

1

While @fusion3k's comment is correct and doing $data = array_merge( $amenitiesObject, $buildingObject ); fixes it, I'd like to explain it a little further so you can avoid this type of scenario.

When you do $data = array($amenitiesObject, $buildingObject);, you are not creating a merge of both arrays, you are creating an array with index 0 equals to $amenitiesObject and index 1 equals to $buildingObject, the equivalent of doing :

array(0 => $amenitiesObject, 1 => $buildingObject);

So the json_encode part is working as expected.

When you use array_merge, you maintain only ONE array, that is a combination on both arrays, so you have the expected result.

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

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.