有没有一种方法来获取与PDO指定列的值进行分组关联数组? [英] Is there a way to fetch associative array grouped by the values of a specified column with PDO?
问题描述
例如,让我们使用一些简单的数据集
For example, let's use some simple data set
+---------+------+------+------------+
| name | age | sex | position |
+---------+------+------+------------+
| Antony | 34 | M | programmer |
| Sally | 30 | F | manager |
| Matthew | 28 | M | designer |
+---------+------+------+------------+
我们正在试图让数组是组织这样
What we are trying to get is array organized this way
Array
(
[Antony] => Array
(
[age] => 34
[sex] => M
[position] => programmer
)
[Sally] => Array
(
[age] => 30
[sex] => F
[position] => manager
)
[Matthew] => Array
(
[age] => 28
[sex] => M
[position] => designer
)
)
作为一个粗略的估计,我们可以使用
As a rough approximation we can use
$pdo->query('SELECT * FROM employee')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
但作为结果,我们有不必要的嵌套层次
But as result we have unnecessary nesting level
Array
(
[Antony] => Array
(
[0] => Array
(
[age] => 34
[sex] => M
[position] => programmer
)
)
[Sally] => Array
(
[0] => Array
(
[age] => 30
[sex] => F
[position] => manager
)
)
[Matthew] => Array
(
[0] => Array
(
[age] => 28
[sex] => M
[position] => designer
)
)
)
我试图用回调函数摆脱这种不必要的嵌套级别的
I tried to get rid of this unnecessary nesting level by using callback function
$stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC|PDO::FETCH_FUNC, 'current');
但由于种种原因它通过不
But for some reasons It passes not
Array
(
[0] => Array
(
[age] => 34
[sex] => M
[position] => programmer
)
)
但只是一堆标量 34,M,程序员
来回调函数:(
您可以使用这些功能的回调看它
You can see it using such function as callback
function what_do_you_pass_me() {
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
};
echo "\n\n";
};
那么,有没有办法使用 PDO来获得期望的结果集:: FETCH _ *
模式,而无需使用 array_map(当前,$结果)
提取后的结果?
So is there a way to get desired resultset using PDO::FETCH_*
modes without using array_map('current', $result)
after fetching results ?
推荐答案
这答案是过时的,请参阅这对方的回答代替。
This answer is out of date, please see this other answer instead.
它看起来像有没有办法做到这一点作为的一部分使用fetchall
。
It looks like there's no way to do this as part of fetchAll
.
您最好的选择将是创建一个扩展PDO类,增加了实用方法吧。
Your best bet is going to be creating a class that extends PDO, adding a utility method to it.
public function queryKeyedAssoc($query, $params, $key) {
$sth = $this->prepare($query);
$sth->execute($params);
$res = array();
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$res[ $row[$key] ] = $row;
return $res;
}
这篇关于有没有一种方法来获取与PDO指定列的值进行分组关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!