convert json Array to a single Json object

advertisements

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'}}


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.