我可以使用PDO :: FETCH_GROUP将结果按两个值分组 [英] Can I use PDO::FETCH_GROUP to group results by two values

查看:412
本文介绍了我可以使用PDO :: FETCH_GROUP将结果按两个值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆