MySQL returns 请求的每个字段有 2 个值

MySQL returns 2 values for every field requested

使用 select 语句执行 query() 时,结果包含字段的两个条目。

$sql = "select first_name, last_name from users";
$rslt = $conn->query($sql);

在上面的示例中,结果将包含数组中的 4 个项目。 2 个键的递增整数,一个键设置为 "first_name",一个键设置为 "last_name"。

Array ( [first_name] => Bill [0] => Bill [last_name] => Johnson [1] => Johnson )

我敢肯定这是一个愚蠢的问题,但是有没有一种快速的方法可以改变返回结果的方式,使每个字段只包含一个键=>值,或者有没有一种方法可以快速删除额外的数据?

我想要的最终数组是两件事之一...

所需结果 1

Array ( [first_name] => Bill [last_name] => Johnson )

要求的结果 2

Array ( [0] => Bill [1] => Johnson )

提前致谢。

如果你使用的是PDO,你可以设置fetch模式

$rslt = $conn->query($sql, PDO::FETCH_ASSOC);

它默认返回两种类型。

有关详细信息,请参阅 http://php.net/manual/en/pdo.query.php

您可以将第二个参数传递给 query() 以更改模式。在您的情况下 PDO::FETCH_ASSOCPDO::FETCH_NUM。我假定默认值为 PDO::FETCH_BOTH,它会在结果数组中创建索引和列名。

查看 fetch 的手册 fetch_style:

PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method

PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class

PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

PDO::FETCH_NAMED: returns an array with the same form as PDO::FETCH_ASSOC, except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name

PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

您想要的是适当的获取样式,而不是 PDO::FETCH_BOTH(默认)作为 fetch() 的第一个参数。

你想做的是使用 PDOStatement 返回的对象 query().

$sql = "select first_name, last_name from users";
$stmt = $conn->query($sql);
$num = $stmt->fetchAll(PDO::FETCH_NUM);
$assoc = $stmt->fetchAll(PDO::FETCH_ASSOC);

我相信这会奏效,但我还没有测试过 fetchAll 是否可以在同一条语句中 运行 两次。