downing1988 2018-02-12 00:49
浏览 39
已采纳

奇怪的JSON密钥?

I'm going to tell you that I'm not expert when it comes to JSON or anything like that. I use it a few times in my projects, but recently I'm using it quite a bit.

Anyway, I'm creating an Android app that sends HTTP post requests to my website. The PHP file retrieves data from a database and converts an array into JSON. Usually, I'll send some data along with the POST request. But because I'm just practising, I'm just displaying all users received from the database to JSON.

However, it's return some weird keys that I don't really want. Example:

[
  {
    0: "1",
    1: "User1",
    2: "userPassword1",
    id: "1",
    username: "User1",
    password: "userPassword1"
  },
  {
    0: "2",
    1: "user2",
    2: "userPassword2",
    id: "2",
    username: "user2",
    password: "userPassword2"
  }
]

It's showing 0, 1, 2, and then the field names. I only want the field names.

My PHP file:

<?php
require 'connection.php';

$rArray = array();

$query = $con->query("SELECT * FROM users");

while ($row = $query->fetch_array()) {
    $rArray[] = $row;
}

echo json_encode($rArray);
?>

How can I fix this?

  • 写回答

2条回答 默认 最新

  • duanluan3651 2018-02-12 00:58
    关注

    Have you tried fetch_assoc?

    Something like this:

    <?php
    require 'connection.php';
    
    $rArray = array();
    
    $query = $con->query("SELECT * FROM users");
    
    while ($row = $query->fetch_assoc()) {
        $rArray[] = $row;
    }
    
    echo json_encode($rArray);
    ?>
    

    For more lesson about fetch_assoc vs. fetch_array you may refer to this thread.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办