0

I have this sql table

I have this sql table

How to return it with php like?

Root1
- SubCat 1
-- SubSubCat 1
- SubCat 2
Root2

I found this, but i cant return it in form, that i need. But the script still displays all categories, first as a sub, and then as root.

How to make it?

4

1 回答 1

1

这可以完成工作:

$items = array(
        (object) array('id' => 42, 'sub_id' => 1),
        (object) array('id' => 43, 'sub_id' => 42),
        (object) array('id' => 1, 'sub_id' => 0),
);

$childs = array();

foreach($items as $item)
    $childs[$item->sub_id][] = $item;

foreach($items as $item) if (isset($childs[$item->id]))
    $item->childs = $childs[$item->id];

$tree = $childs[0];

print_r($tree);

这通过首先按 parent_id 索引类别来工作。然后对于每个类别,我们只需将 category->childs 设置为 childs[category->id],然后树就构建好了!

所以,现在 $tree 是类别树。它包含一个 sub_id=0 的项目数组,这些项目本身包含一个他们的孩子的数组,他们自己...

print_r($tree) 的输出:

stdClass Object
(
    [id] => 1
    [sub_id] => 0
    [childs] => Array
    (
        [0] => stdClass Object
            (
                [id] => 42
                [sub_id] => 1
                [childs] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 43
                                [sub_id] => 42
                            )

                    )

            )

    )

)

所以这是最终的功能:

function buildTree($items) {

    $childs = array();

    foreach($items as $item)
        $childs[$item->sub_id][] = $item;

    foreach($items as $item) if (isset($childs[$item->id]))
        $item->childs = $childs[$item->id];

    return $childs[0];
}

$tree = buildTree($items);
于 2013-03-27T14:51:19.553 回答