有没有办法获取按 PDO 指定列的值分组的关联数组?
例如,让我们使用一些简单的数据集
+---------+------+------+------------+
| name | age | sex | position |
+---------+------+------+------------+
| Antony | 34 | M | programmer |
| Sally | 30 | F | manager |
| Matthew | 28 | M | designer |
+---------+------+------+------------+
我们试图得到的是以这种方式组织的数组
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
)
)
作为粗略的近似值,我们可以使用
$pdo->query('SELECT * FROM employee')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
但结果是我们有不必要的嵌套级别
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
)
)
)
我试图通过使用回调函数来摆脱这个不必要的嵌套级别
$stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC|PDO::FETCH_FUNC, 'current');
但是由于某些原因,它没有通过
Array
(
[0] => Array
(
[age] => 34
[sex] => M
[position] => programmer
)
)
但只是一堆标量来回调函数:(34, 'M', 'programmer'
您可以使用回调等函数来查看它
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('current', $result)