如何以这种方式格式化我的JSON?

时间:2014-01-24 11:09:08

标签: php 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);

我需要改变什么?

3 个答案:

答案 0 :(得分:4)

$arr[]代替$arr

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

答案 1 :(得分:2)

试试这个:

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

答案 2 :(得分: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.