我可以使用 PDO::FETCH_GROUP 按两个值对结果进行分组吗 [英] Can I use PDO::FETCH_GROUP to group results by two values
问题描述
我使用 PHP 和 PDO 从数据库中检索一组值,然后按第一列分组,代码如下:
I'm using PHP and PDO to retrieve a set of values from a database and then group by the first column, with this code:
$result = $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_NUM);
这意味着如果我的数据是这种格式:
This means that if my data is in this format:
|Column1 |Column2 |Column3|
|1 |2 |a|
|1 |2 |b|
它返回它:
1: {
[Column2: 2, Column3: a],
[Column2:2, Column3:b]
}
我将如何按 Column1 和 Column2 分组,以便得到类似的结果:
How would I group by Column1 and Column2 so I get something like:
1:
{
2:
{
Column3: a,
Column3:b
}
}
这可能与 PDO 常量的组合有关吗?
Is that possible to do with a combination of PDO constants?
谢谢
推荐答案
如您所见,通过使用 PDO::FETCH_GROUP
将数组与指定的列分组,可以轻松地重建数组.您需要的是将二维数组(来自数据库的结果)转换为三维数组,但是不可能以这种方式重建它.
As you saw, it is possible easy to rebuild array easily by grouping it with one specified column with PDO::FETCH_GROUP
. The thing you are need is to convert 2-dimension array (result from database) to 3-dimensional array, but it is not possible to rebuild it this way.
您需要通过嵌套循环手动完成.很简单,就像这些:
You need to do it manually via nested loops. It's pretty simple, like these:
// let's assume $result is:
$result = [
[1, 2, 'a'],
[1, 2, 'b']
];
$newResult = [];
foreach( $result as $row ) {
$newResult[$row[0]][$row[1]][] = $row[2];
}
var_dump($newResult);
它返回:
array(1) {
[1]=>
array(1) {
[2]=>
array(2) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
}
}
}
它看起来就像你需要的一样.
and it look like what you needed.
这篇关于我可以使用 PDO::FETCH_GROUP 按两个值对结果进行分组吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!