简体   繁体   中英

Get all children items from flat array with nested data structure

I have a flat array of categories. All categories have ID, Parent_id and Name.

The root categories have Parent_id equal to null. They have subcategories that might have them as their parents and their might be subsubcategories that have subcategories as parents. (their might be a lot of levels). I can get all categories with a single query into a flat array. What I need is - If I take a category (or a subcaegory), how can I get a list of all nested categories (subcategories, subsubcategories) that are included in this category? Got stack with that problem :(

Array looks like this:

Array
(
[0] => Array
    (
        [pk_i_id] => 2
        [fk_i_parent_id] => 
        [i_expiration_days] => 30
        [i_position] => 0
        [b_enabled] => 1
        [b_price_enabled] => 1
        [s_icon] => 
    )

[1] => Array
    (
        [pk_i_id] => 4
        [fk_i_parent_id] => 
        [i_expiration_days] => 30
        [i_position] => 6
        [b_enabled] => 1
        [b_price_enabled] => 1
        [s_icon] => 
    )

[2] => Array
    (
        [pk_i_id] => 12
        [fk_i_parent_id] => 
        [i_expiration_days] => 60
        [i_position] => 11
        [b_enabled] => 1
        [b_price_enabled] => 1
        [s_icon] => 
    )

[3] => Array
    (
        [pk_i_id] => 13
        [fk_i_parent_id] => 108
        [i_expiration_days] => 30
        [i_position] => 0
        [b_enabled] => 1
        [b_price_enabled] => 1
        [s_icon] => 
    )

You can use recursion. It will be looks like this:

function outTree(array $tree, $parentId = null) {
    echo '<ul>';
    foreach ($tree as $row) {
        if ($row['fk_i_parent_id'] == $parent_id) {
            echo '<li>' . $row['pk_i_id'];
            echo outTree($tree, $row['pk_i_id']);
            echo '</li>';
        }
    }
    echo '</ul>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM