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對象?我在上面的代碼中錯誤地做了什麼?
謝謝。
這兩個json都是無效的,你需要在**「b」之前加逗號:** – Gowri
你應該發佈程序的* actual *輸出 – meagar