我正在尝试从MySQL获取数据并以JSON格式显示它
这是部分PHP代码
$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo json_encode($row),"<br/>";}
&GT?; 我正在输出
{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"}
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}
但我需要它
food1:[
{"item":"dosa","cost":"20","veg":"0","spicy_level":"1"},
{"item":"idli","cost":"20","veg":"0","spicy_level":"2"}
]
任何人都可以指导我吗? 我认为我得到的是对象格式,我需要以数组格式输出,即[&amp; ]。 这个json和php非常新。
答案 0 :(得分:0)
您可以将查询结果封装在数组中并在打印后填充;
$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);
$a = array();
while($row = $result->fetch_assoc()) {
if($a['food1'] ==null)
$a['food1'] = array():
array_push($a['food1'],$row);}
echo json_encode($a);
?></i>
答案 1 :(得分:0)
您的代码应为:
$sql = "SELECT item, cost, veg, spicy_level FROM food1";
$result = $conn->query($sql);
$food['food1'] = array();
while($row = $result->fetch_assoc()) {
$food['food1'][] = $row;
}
echo json_encode($food);
答案 2 :(得分:0)
每次循环都不要调用json_encode
。将所有行放入一个数组中,然后对其进行编码。
$food = array();
while ($row = $result->fetch_assoc()) {
$food[] = $row;
}
echo json_encode(array('food1' => $food));