0

这是我的数组输出

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
4

1 回答 1

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);
    }
}
于 2013-01-05T20:41:27.883 回答