按特定键对数组进行分组-PHP

时间:2018-12-14 23:42:13

标签: php arrays sorting

我想按此数组分组:

$arr = [
    ['id' => 1, 'name' => 'a'],
    ['id' => 2, 'parent' => 1, 'name' => 'a-child'],
    ['id' => 3, 'parent' => 1, 'name' => 'a-child-2'],
    ['id' => 4, 'name' => 'c'],
];

要这样:

['id' => 1, 'name' => 'a', 'child' => [
    ['id' => 2, 'parent' => 1, 'name' => 'a-child'],
    ['id' => 3, 'parent' => 1, 'name' => 'a-child-2'],
]],
['id' => 4, 'name' => 'c'],

或按特定键将它们分组,该键将是父元素。 我正在使用PHP

1 个答案:

答案 0 :(得分:0)

您可以将其用于1级深度。

$arr = [
    ['id' => 1, 'name' => 'a'],
    ['id' => 2, 'parent' => 1, 'name' => 'a-child'],
    ['id' => 3, 'parent' => 1, 'name' => 'a-child-2'],
    ['id' => 4, 'name' => 'c'],
];


$new = [];

foreach($arr as $key => $row) {
    if(!isset($row['parent'])) $new[$row['id']] = $row;
}

foreach($arr as $key => $child) {
    if(isset($child['parent'])) { 
        $new[$child['parent']]['child'][] = $child;
    }
}

print_r($new);