I converted a PHP array into JSON, using json_encode. I checked the console, and the objects are displaying in array, but as individual objects.
[ { Object { 03-13-2012="Jazz"}, Object { 07-19-2012="Pop"}, ... ]
How can I convert this array into one object, like this (in PHP or jQuery):
Object { 03-13-2012="Jazz", 07-19-2012="Pop"}
Edit: Here's the beginning of my print_r for the PHP array:
Array
(
[0] => Array
(
[03-13-2012] => Jazz
)
[1] => Array
(
[07-19-2012] => Pop
)
)
To convert an array to json in PHP, use the json_encode() function. The json_encode() function is used to encode a value to JSON format. The json_encode() function converts PHP-supported data type into JSON formatted string to be returned due to JSON encode operation.
To convert PHP array to JSON, use the json_encode() function. The json_encode() is a built-in PHP function that converts an array to json. The json_encode() function returns the string containing a JSON equivalent of the value passed to it, as demonstrated by the numerically indexed array.
PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.
You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.
In general, you need to prepare such a PHP array, which then should be json_encode and passed along to the server:
$data = array(
'03-13-2012' => 'Jazz',
'07-19-2012' => 'Pop',
);
echo json_encode( $data );
exit;
Don't be afraid of loops
$output = array();
foreach($data as $v) {
$output[key($v)] = current($v);
}
echo json_encode($output, 128);
See Live Demo
You'll want to iterate over the indexed array making the keys of an associative array found therein into keys in a second associative array.
Assumption: You're starting with a JSON string, and you want to end up with a JSON string.
Warning: If you encounter duplicates you will overwrite.
Here's an example of what I'm talking about:
<?php
$foo = json_decode('[{"abc":"A123"},{"xyz":"B234"}]');
$bar = array();
foreach ($foo as $f) {
foreach ($f as $k => $v) {
$bar[$k] = $v;
}
}
echo json_encode($foo)."\n";
echo json_encode($bar)."\n";
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With