0

I was wonder whether it is possible to convert a json Array to a single json object in php?

I mean below json Array:

[{'x':'y','k':'l'}, {'q':'w', 'r':'t'}] 

Can be converted to:

{'0':{'x':'y','k':'l'}, '1':{'q':'w', 'r':'t'}}
2
  • 1
    Then it will become a 1D array Commented Aug 12, 2016 at 8:16
  • "You keep using that word. I do not think it means what you think it means." There is no such thing as a "JSON Object". Commented Aug 13, 2016 at 21:17

2 Answers 2

2

Use json_encode with the JSON_FORCE_OBJECT parameter

$json = "[{'x':'y','k':'l'}, {'q':'w', 'r':'t'}]";
$array = json_decode($json, true);  // convert our JSON to a PHP array
$result = json_encode($array, JSON_FORCE_OBJECT); // convert back to JSON as an object

echo $result; // {"0":{"x":"y","k":"l"},"1":{"q":"w","r":"t"}}

JSON_FORCE_OBJECT

Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

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

Comments

0

Please try below code.

$array[] = array('x' => 'y','k' => '1');
$array[] = array('q' => 'w','r' => 't');
echo json_encode($array,JSON_FORCE_OBJECT);

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.