2011-09-13 94 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;