我试图从我的数据库中获取一个JSON字符串,但数据库返回多行数据,当JSON编码时,不适合使用正确的格式。
我当前的PHP代码
$conn = [omitted];
$sql = [omitted];
$result = $conn->query($sql); //this query has been proven to work
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$row[] = array_merge($row,$rows);
}
echo json_encode($rows);
} else {
echo "0";
}
但是此代码在$rows
数组与$row
数组合并之前回显了。
当前结果:
[]
通缉结果:
[{"id":"1","team_name":"[omitted]","has_finished":"0"},{"id":"2","team_name":"[omitted]","has_finished":"0"},{"id":"3","team_name":"[omitted]","has_finished":"0"},{"id":"4","team_name":"[omitted]","has_finished":"0"},{"id":"5","team_name":"[omitted]","has_finished":"0"},{"id":"6","team_name":"[omitted]","has_finished":"0"},{"id":"7","team_name":"[omitted]","has_finished":"0"}]
答案 0 :(得分:0)
您永远不会将任何数据分配到$ rows数组中。要将每一行分配到数组中,您需要将其作为循环。
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}