dq_1984 2016-02-20 12:42
浏览 254
已采纳

如何在PHP foreach循环中对数据库中的记录进行分组,然后将值合并到一个新数组中?

I have a table in a MySQL database that is used to store games that someone can book on. The games can be held in more than one location but they can also share the same time as another game. Here is an example of the data in the array that is taken from the MySQL database:

[0] => Array
    (
        [id] => 174
        [gamedatetime] => DateTime Object
            (
                [date] => 2016-02-08 14:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/London
            )

        [available] => 1
        [gameID] => 1
        [isBooked] => 
    )

[1] => Array
    (
        [id] => 175
        [gamedatetime] => DateTime Object
            (
                [date] => 2016-02-08 14:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/London
            )

        [available] => 1
        [gameID] => 1
        [isBooked] => 1
    )

[2] => Array
    (
        [id] => 176
        [gamedatetime] => DateTime Object
            (
                [date] => 2016-02-08 15:00:00.000000
                [timezone_type] => 3
                [timezone] => Europe/London
            )

        [available] => 1
        [gameID] => 1
        [isBooked] => 
    )

What I need to do is create an array with this data on it, but grouped by the date and time, and the gameID are joined together but comma separated, like this:

[0] => Array
    (
        [gamedatetime] => 2016-02-08 14:00:00.000000
        [id] => 174,175
    )
[1] => Array
    (
        [gamedatetime] => 2016-02-08 15:00:00.000000
        [id] => 176
    )

How can I achieve this using PHP?

  • 写回答

3条回答 默认 最新

  • dongyanhu5628 2016-02-20 12:53
    关注

    The following will achieve what you are aiming for but the ids will be in a subarray, allowing you to concatenate together as you need them.

    $newArray = [];
    foreach ($oldArray as $game) {
        $newArray[$game['gamedatetime']]['gamedatetime'] = $game['gamedatetime'];
        $newArray[$game['gamedatetime']]['ids'][] = $game['id'];
    }
    

    or you can change the query to something like:

    SELECT gamedatetime, GROUP_CONCAT(id) as `id`
    FROM game
    WHERE ...
    GROUP BY gamedatetime
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?