从数据库输出JSON数据

时间:2017-08-08 06:46:35

标签: php json database fetch

您好,我从我的数据库中获取了以下JSON数据:

[{
    "0": "1",
    "id": "1",
    "1": "Hakob",
    "name": "Hakob",
    "2": "abc@email.com",
    "email": "abc@email.com"
}, {
    "0": "2",
    "id": "2",
    "1": "Arsen",
    "name": "Arsen",
    "2": "zxc@email.com",
    "email": "zxc@email.com"
}]

我不希望看到以下键/值"0": "1","1": "Hakob","2": "abc@email.com",和其他行相同。 谁现在做了什么,以及我如何删除它们。

这是我获取此内容的PHP脚本

$sql = "SELECT * FROM contacts";
$result = mysqli_query($connect, $sql);
$response = array();
while ($row = mysqli_fetch_array($result)) {
    $response[] = $row;
}

print json_encode($response);

// Close connection
mysqli_close($connect);

1 个答案:

答案 0 :(得分:1)

你只需要通过mysqli_fetch_array的第二个参数来获得所需的结果

$sql = "SELECT * FROM contacts";
$result = mysqli_query($connect, $sql);
$response = array();

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //<-----------change this
    $response[] = $row;
}

print json_encode($response);

// Close connection
mysqli_close($connect);

修改

或者您可以使用mysqli_fetch_assoc($result)来获取关联数组

请参阅手册:http://php.net/manual/en/mysqli-result.fetch-array.php

http://php.net/manual/en/mysqli-result.fetch-assoc.php