开发者

PHP Array to JSON

开发者 https://www.devze.com 2023-04-04 23:00 出处:网络
I\'m trying to build a JSON object from a mysql query. The JSON structure that I\'m striving for should look like this:

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",
               开发者_如何学C     "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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消