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
        )
)
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

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;

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";
?>

Comments

Your Answer

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.