2016-06-11 64 views
0

我需要制作一个PHP JSON像这样从MySQL数据库使用PHP:PHP:生成没有{}的json?

[['Staff Welfare', 'london', 'map-marker-icon.png'] , ['perfect', 'London', 'map-marker-icon.png'] , ['Fare Trade', 'essex', 'map-marker-icon.png'] , ['Fare Trade', 'london', 'map-marker-icon.png'] ,] 

这是我已经试过:

$return_arr = array(); 
$sql = "SELECT * FROM restaurants"; 
if ($result = mysqli_query($db_conx, $sql)){ 
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 

    $row_array['id'] = $row['id']; 
    $row_array['location'] = $row['location']; 
    $row_array['name'] = $row['name']; 
    $row_array['type'] = $row['type']; 


    array_push($return_arr,array($row_array)); 
    } 
} 

mysqli_close($db_conx); 

echo json_encode($return_arr); 

但上面的代码回声的是这样的:

[[{"id":"1","location":"london","name":"Staff","type":"indian"}], [{"id":"2","location":"London","name":"perfect","type":"chinese"}],[{"id":"3","location":"essex","name":"Trade","type":"kebab"}],[{"id":"5","location":"london","name":"Fare Trade","type":"kebab"}]] 

有人可以请让我知道我可以如何删除{}并删除column names以及我的j儿子回声就像我在找什么?

+2

那需要的格式是无效的JSON它甚至不接近JSON –

+1

它有效的JSON,你必须1)更改'''''''2)在结尾']'之前删除'''。 –

回答

3

您必须摆脱数组键才能生成json而不使用{}。将array_push代码更改为:

array_push($return_arr, array_values($row));

array_values函数将只返回没有键的$row值。

+0

谢谢。这有助于实现我正在尝试做的事情... – Jackson

2

你引述所需JSON是无效的,但如果你改变了'"和除去最后一次,这将是有效的:所有这些

[ 
    ["Staff Welfare", "london", "map-marker-icon.png"], 
    ["perfect", "London", "map-marker-icon.png"], 
    ["Fare Trade", "essex", "map-marker-icon.png"], 
    ["Fare Trade", "london", "map-marker-icon.png"] 
] 

这就是含含每三个条目数组的数组,是字符串。

如果您不想在JSON中使用对象,请勿将关联数组推送到PHP中的结果数组中。

while循环应该是:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 
    array_push($result_arr, array(
     $row['name'], 
     $row['location'], 
     $row['some-field-you-have-not-shown-giving-image-link'] 
    )); 
} 

注意什么正在推是有三个条目一个无聊的非关联数组。 (还要注意,你没有显示哪个列名给出图像链接,所以我已经使用了上述的描述性的)。