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条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址