在While循环中合并多个数组对象然后JSON编码

时间:2017-05-06 03:17:22

标签: php arrays json while-loop

我试图从我的数据库中获取一个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"}]

1 个答案:

答案 0 :(得分:0)

您永远不会将任何数据分配到$ rows数组中。要将每一行分配到数组中,您需要将其作为循环。

while($row = $result->fetch_assoc()) {
  $rows[] = $row;
}