我一直在搜索这个站点,并且绞尽脑汁试图打印一个不包含索引的json_encode结果。
下面是PHP/MySQL从数据库中获取数据的函数:public function listGuestsAll() {
if(is_null($this->pdo)) {
$this->msg = 'Connection Failed!';
return [];
} else {
$pdo = $this->pdo;
$stmt = $pdo->prepare('SELECT user_id, name_first, name_last, email_address, user_role FROM guestList');
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
…下面是print_r代码:
print_r(json_encode($user->listGuestsAll()));
…下面是输出:
[
{
"user_id":"1",
"0":"1",
"name_first":"John",
"1":"John",
"name_last":"Doe",
"2":"Doe",
"email_address":"john@doe.com",
"3":"john@doe.com",
"user_role":"1",
"4":"1"
},
{
"user_id":"2",
"0":"2",
"name_first":"Jane",
"1":"Jane",
"name_last":"Doe",
"2":"Doe",
"email_address":"jane@doe.com",
"3":"jane@doe.com",
"user_role":"1",
"4":"1"
}]
我如何让它输出没有重复字段索引为0:1,1:John, 2:Doe, 3:john@doe, 4:1等?
提前感谢!
您正在使用它来获取行:
$result = $stmt->fetchAll();
文档说明默认的获取模式是PDO::FETCH_BOTH
,这意味着返回的结果同时包含作为键和数字键的列名。
可以指定获取模式。要获取仅由数字键索引的行,请使用:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
要获取仅按列名索引的行,使用:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
你也可以全局改变默认值,这样当你没有指定一个获取模式时,它会影响你所有的获取:
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NUM);
你应该读:
- https://www.php.net/manual/en/pdostatement.fetch.php
- https://www.php.net/manual/en/pdostatement.fetchall.php
- https://www.php.net/manual/en/pdo.setattribute.php