2011-09-13 67 views
0

我想从一个MySQL查询建立一个JSON对象。我正在努力争取的JSON结构应该是这样的:PHP的阵列到JSON

{ 
     "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" 
      } 
      ] 
} 

然而,我的代码总是返回包裹在一个阵列,像这样一个JSON对象:

[ 
     { 
      "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" 
       } 
       ] 
    } 
] 

这里是PHP代码我使用:

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

我想知道:为什么我得到一个数组中包装的JSON对象?我在上面的代码中错误地做了什么?

谢谢。

+1

这两个json都是无效的,你需要在**“b”之前加逗号:** – Gowri

+0

你应该发布程序的* actual *输出 – meagar

回答

4

以下两行创建一个元素的关联数组和一元件阵列附加到您的较大$json_data阵列:

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

相反,只需添加一个新的键/值对到原始数组:

$json_data[$blog] = $ablog;