Reputation: 1126
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
)
)
Upvotes: 12
Views: 55827
Reputation: 11999
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;
Upvotes: 7
Reputation: 95121
Don't be afraid of loops
$output = array();
foreach($data as $v) {
$output[key($v)] = current($v);
}
echo json_encode($output, 128);
Upvotes: 24
Reputation: 155
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";
?>
Upvotes: 1