我有这个代码从MYSQL数据库获取一些字段。问题是php显得纯白。但是如果我删除了while的元素并且只留下一个,
,则数组打印正常。
$sql = "SELECT rest.img,rest.rest_name,horario.desc_hor, rest.descp, rest.rest_id FROM rest, type, horario WHERE rest.type_id = type.type_id AND rest.id_hor = horario.id_hor AND rest.type_id=1";
$result = $conn->query($sql);
$cnt = $result->num_rows;
$json = array();
if($cnt>0){
while($row = $result->fetch_assoc()){
$json['']=$row['img'];
$json['']=$row['rest_name'];
$json['']=$row['desc_hor'];
$json['']=$row['descp'];
$json['']=$row['rest_id'];
}
}
print( json_encode($json));
答案 0 :(得分:0)
您的代码存在的问题是您没有自动分配索引。您始终为数组中的所有列和行分配索引['']
。
试试这个......
$json = array();
while($row = $result->fetch_assoc()){
array_push($json, $row);
}
echo json_encode($json);
或者这......
$json = array();
while($row = $result->fetch_assoc()){
$json[] = $row;
}
echo json_encode($json);
无论哪种方式,都会在数组中生成自动索引。