Reputation: 314
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'}}
Upvotes: 0
Views: 1115
Reputation: 720
Please try below code.
$array[] = array('x' => 'y','k' => '1');
$array[] = array('q' => 'w','r' => 't');
echo json_encode($array,JSON_FORCE_OBJECT);
Upvotes: 0
Reputation: 5913
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.
Upvotes: 2