2014-01-24 86 views
3

我試圖輸出JSON格式如下:如何以這種方式格式化我的JSON?

[{"name":"venue 1"}, {"name":"venue 2"}, {"name":"venue 3"}] 

但它現在出來是這樣的:

{"name":"venue 1"}{"name":"venue 2"}{"name":"venue 3"} 

這裏是我的代碼:

query = "SELECT * FROM venues"; 
$result = mysqli_query($con, $query); 

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) { 

    $arr = array(
    'name'=> $row['name'] 
    ); 

    print json_encode($arr); 

做什麼,我需要改變?

+0

停止輸出while循環中的所述數據;將場地的__all__構建成循環中的數組,然後json編碼__after__完成循環 –

回答

4

添加$arr[]這一翻譯的$arr

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) { 
$arr[] = array('name'=> $row['name']); 
} 
echo json_encode($arr); 
+0

謝謝,這確實有效。 – Sebastian

2

嘗試這種情況:

$arr[] = array(
'name'=> $row['name'] 
); 
0
Simply make an array like 

$array[]["name"]="value1"; 
$array[]["name"]="value2"; 
$array[]["name"]="value3"; 
echo json_encode($array); 

you will get the json data as: 
[{"name":"value1"},{"name":"value2"},{"name":"value3"}] 
which you wants. You have to make the array using looping statements according to your need.