12

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
 )
)
asked Aug 25, 2013 at 19:36
2
  • 3
    What does your PHP array look like? (Use print_r.) Commented Aug 25, 2013 at 19:37
  • 1
    Simply merge each of the inner arrays in PHP or the objects in JS. Better yet, create the array in the correct format from the beginning! Commented Aug 25, 2013 at 19:41

3 Answers 3

24

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

answered Aug 25, 2013 at 19:51
Sign up to request clarification or add additional context in comments.

1 Comment

@Baba I am using return instead of echo because I need json response for mobile applications but return only returns last value of an array can you tell me how I can return whole array?
7

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;
PJunior
2,7581 gold badge35 silver badges30 bronze badges
answered Aug 25, 2013 at 19:40

Comments

1

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";
?>
answered Aug 25, 2013 at 19:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.