如何按父ID分组数组

时间:2013-01-05 19:49:11

标签: php arrays

这是我的数组输出

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => Category A
            [parent] => 0
        )
    [2] => Array
        (
            [id] => 2
            [name] => Sub Cat A - 1
            [parent] => 1
        )
    [3] => Array
        (
            [id] => 3
            [name] => Sub Cat A - 2
            [parent] => 1
        )
    [4] => Array
        (
            [id] => 4
            [name] => Sub Cat A 2 - 1
            [parent] => 3
        )
    [5] => Array
        (
            [id] => 5
            [name] => Category B
            [parent] => 0
        )
    [6] => Array
        (
            [id] => 6
            [name] => Sub Cat B - 1
            [parent] => 5
        )
    [7] => Array
        (
            [id] => 7
            [name] => Category C
            [parent] => 0
        )
)

我试过这个但错误的输出。

foreach ($categories as $key => $category) {
    $group[$category['parent']][$key] = $category;
}

问题:如何重组数组&我的欲望输出应该像

Category A
    Sub Cat A - 1
    Sub Cat A - 2
        Sub Cat A 2 - 1
Category B
    Sub Cat B - 1
Category C

1 个答案:

答案 0 :(得分:2)

试试这段代码;

<?php
$as // your array
$new_as = array();
foreach ($as as $ind => $a) {
    $new_as[$a['id']] = $a;
    $new_as[$a['id']]['children'] = array();
}

foreach ($new_as as $ind => &$new_a) {
    $parent = $new_as[$ind]['parent'];
    if(isset($new_as[$parent])){
        $new_as[$parent]['children'][] = & $new_as[$ind];
    }
}
echo '<pre>';
foreach ($new_as as $ind => &$new_a) {
    if ($new_a['parent'] == 0) {
        echo $new_a['name'];
        echo "\n";
        print_children($new_a['children'],1);
    }
}
echo '</pre>';    
function print_children($children, $level = 0)
{
    foreach ($children as $child) {
        echo str_repeat("    ", $level);
        echo $child['name'];
        echo "\n";
        print_children($child['children'], $level + 1);
    }
}