douwen4401 2015-10-12 18:43
浏览 55
已采纳

为什么我的简单PHP查询返回重复值?

When I use PHP to do a simple query on a MySQL database, the object being returned holds duplicate values.

This is the PHP code where I query the database:

$query = 'SELECT * FROM names';
$result = mysqli_query($connection, $query);

$data = array();
while ($row = mysqli_fetch_array($result)) {
    array_push($data, $row);
}

echo json_encode($data);

The returning JSON object (being outputted by the Chrome console through Javascript) is as follows:

[{"0": "1", "id": "1", "1": "Jeff", "name": "Jeff"},
 {"0": "2", "id": "2", "1": "Andrew", "name": "Andrew"}]

Each value is listed twice: once as its correct column name and once as its column name's index. Does anyone know why this is happening?

  • 写回答

1条回答 默认 最新

  • douju6850 2015-10-12 18:47
    关注

    mysqli_fetch_array() returns both a numerical and asssociative array of the resultset. You need to use mysql_fetch_assoc() to get just the associative array.

    while ($row = mysqli_fetch_assoc($result)) {
        array_push($data, $row);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?