构建多维数组的最佳方法(类别;子类别;子子类别等)

时间:2014-12-08 13:53:41

标签: php multidimensional-array

您好我的sql查询得到了这个回复:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Category #1
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 2
            [name] => Category #2
            [parent] => 0
        )

    [2] => Array
        (
            [id] => 3
            [name] => Category #3
            [parent] => 0
        )

    [3] => Array
        (
            [id] => 4
            [name] => Category #4
            [parent] => 0
        )

    [4] => Array
        (
            [id] => 5
            [name] => Sub category of category #1
            [parent] => 1
        )

    [5] => Array
        (
            [id] => 6
            [name] => Sub category of category #2
            [parent] => 2
        )

    [6] => Array
        (
            [id] => 7
            [name] => Sub category of category #6 (which is sub category of category #2)
            [parent] => 6
        )
)

转换后,响应必须如下所示:

array
(
    array
        (
            [id] => 1
            [name] => Category #1
            [parent] => 0
            [children]=> array
                (
                    [id] => 5
                    [name] => Sub category of category #1
                    [parent] => 1
                )
        )

    array
        (
            [id] => 2
            [name] => За дома
            [parent] => 0
            [children]=> array
                (
                    [id] => 6
                    [name] => Sub category of category #2
                    [parent] => 2
                    [children] => array
                        (
                            [id] => 7
                            [name] => Sub category of category #6 (which is sub category of category #2)
                            [parent] => 6
                        )
                )
        )

    array
        (
            [id] => 3
            [name] => Category #3
            [parent] => 0
        )

    array
        (
            [id] => 4
            [name] => Category #4
            [parent] => 0
        )
)

我的问题是 - 构建这样一个多维数组的最佳方法是什么(例如在php中)。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

$arr = 'Your array';

$new = array();
foreach ($arr as $a){
    $new[$a['parent']][] = $a;
}
$data = createMyTree($new, array($arr[0]));
print_r($data);

function createMyTree(&$list, $parent){
    $tree = array();
    foreach ($parent as $k=>$l){
        if(isset($list[$l['id']])){
            $l['children'] = createMyTree($list, $list[$l['id']]);
        }
        $tree[] = $l;
    } 
    return $tree;
}

答案 1 :(得分:0)

您可以将数据存储在常规数组中,并使用代码将其遍历回来。因此每个节点都有其parentId,并且只要parentId不为0,您就会遍历另一个父节点,直到到达给定节点的根父节点。

你真的不需要把它想象成一个多维数组;由于无限的尺寸,你将无法做任何事情。在其他语言中,例如C,您可以使用指针构建树实现(经典数据结构)。但在PHP中,我只使用一个平面数组,存储parentId,并使用代码递归。