按指定列对二维数组的行进行分组,并将行推入子数组中[重复]

问题描述 投票:0回答:1

我对如何根据公共值重新组合数组有点困惑。这是下面的数组:

Array
(
[0] => Array
    (
            [team] => 1
            [id] => 5
            [user] => teamleader1
            [Designation] => Team Leader
    )
[1] => Array
    (
        [team] => 1
        [id] => 6
        [user] => consultant1
        [Designation] => Consultant
    )

[2] => Array
    (
        [team] => 1
        [id] => 7
        [user] => consultant2
        [Designation] => Consultant
    )

[3] => Array
    (
        [team] => 2
        [id] => 8
        [user] => consultant3
        [Designation] => Consultant
    )

[4] => Array
    (
        [team] => 2
        [id] => 9
        [user] => teamleader2
        [Designation] => Team Leader
    )

)

我想按其团队价值对其进行分组,如下所示:

数组
(
[1] => 数组
    (
    [0] => 数组(
         [团队] => 1
         [id] => 5
         [用户] =>队长1
         [职务] => 团队负责人
     )
    [1] => 数组(
         [团队] => 1
         [id] => 6
         [用户] =>顾问1
         [职称] => 顾问
     )
    [2] => 数组(
         [团队] => 1
         [id] => 7
         [用户] =>顾问2
         [职称] => 顾问
     )
)
[2] => 数组
    (
    [0] => 数组(
         [团队] => 1
         [id] => 8
         [用户] =>顾问3
         [职称] => 顾问
     )
    [1] => 数组(
         [团队] => 1
         [id] => 9
         [用户] =>队长2
         [职务] => 团队负责人
     )
    )
)

两个主要阵组是队伍本身。

php arrays multidimensional-array grouping sub-array
1个回答
2
投票
<?php
$grouped = array();
foreach ($yourData as $item) {
  // copy item to grouped
  $grouped[$item['team']][] = $item;
}
var_dump($grouped);

演示

© www.soinside.com 2019 - 2024. All rights reserved.