0

I'm trying to build a JSON object from a mysql query. The JSON structure that I'm striving for should look like this:

   {
        "a": [
            {
                "user": "alb",
                "time": "2011-09-12 05:56:36"
            },
            {
                "user": "arg",
                "time": "2011-09-12 05:56:36"
            }
             ]
        "b": [
            {
                "user": "blah",
                "time": "2011-09-12 05:56:36"
            },
            {
                "user": "bleh",
                "time": "2011-09-12 05:56:36"
            }
             ]
}

However, my code always returns a JSON object wrapped in an array like so:

[
       {
            "a": [
                {
                    "user": "alb",
                    "time": "2011-09-12 05:56:36"
                },
                {
                    "user": "arg",
                    "time": "2011-09-12 05:56:36"
                }
                 ]
            "b": [
                {
                    "user": "blah",
                    "time": "2011-09-12 05:56:36"
                },
                {
                    "user": "bleh",
                    "time": "2011-09-12 05:56:36"
                }
                 ]
    }
]

Here is the php code I'm using:

<?php
$json_data = array();
foreach($blogs as $blog)
{
    $sql    = "SELECT * from users";
    $query  = mysql_query($sql);
    $ablog   = array();
    while ($row = mysql_fetch_assoc($query))
    {
        $json_element = array(
        "user"=> $row[username] ,
        "time"=> $row[time]
        );
        array_push($ablog,$json_element);
    }
    $eblog = array($blog => $ablog);
    array_push($json_data,$eblog);

}
$json_output = json_encode($json_data);
print $json_output;
?>

I was wondering: Why am I getting a JSON object wrapped in an array? What am I doing incorrectly in the code above?

Thank you.

2
  • 1
    Both json is invalid you need to add comma before "b": Commented Sep 13, 2011 at 4:42
  • You should post the actual output of your program Commented Sep 13, 2011 at 4:50

1 Answer 1

4

The following two lines are creating one-element associative arrays and appending the one-element array to your larger $json_data array:

$eblog = array($blog => $ablog);
array_push($json_data,$eblog);

Instead, just add a new key/value pair to your original array:

$json_data[$blog] = $ablog;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.