合并数组中的重复条目

时间:2014-08-19 09:00:22

标签: php arrays merge items

我坚持简单的事情(至少我认为这很简单),

我有一个带有重复条目的数据库输出,我想合并它们。输出如下:

 ID   Name   Week   Active
 1    Steve  10     true
 2    Steve  11     false 
 3    Steve  12     true
 4    John   10     true
 5    John   11     false
 6    Emma   10     true
 7    Jane   11     true

所以数组应如下所示:

[
    [0] => [
        'id'     => 1,
        'name'   => 'Steve',
        'weeks' => [
             [0]  => [
                 'active' => true,
                 'week'   => 10
             ],
             [1]  => [
                 'active' => false,
                 'week'   => 11
             ],
             [2]  => [
                 'active' => true,
                 'week'   => 12
             ]
         ]  
    ],
    [1] => [
        'id'     => 2,
        'name'   => 'John',
        'weeks' => [
             [0]  => [
                 'active' => true,
                 'week'   => 10
             ],
             [1]  => [
                 'active' => false,
                 'week'   => 11
             ]
         ]  
    ],
    [2] => [
        'id'     => 3,
        'name'   => 'Emma',
        'weeks' => [
             [0]  => [
                 'active' => true,
                 'week'   => 10
             ]
         ]  
    ],
    [3] => [
        'id'     => 4,
        'name'   => 'Jane',
        'weeks' => [
             [0]  => [
                 'active' => false,
                 'week'   => 11
             ]
         ]  
    ]
]

容易完成吗?

1 个答案:

答案 0 :(得分:0)

您可以使用JSON作为解决方法,其中字典中的重复项可以转换为数组,请参见https://stackoverflow.com/a/61416136/7471760