0
votes

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] => 
    )
1
Would you like to give us a bit of a visual clue as to what this array looks like please, then also an example of what yoo want out as a result. Otherwise people are just going to ignore ths question. And have a look at the perfect questionRiggsFolly
It strikes me it would be easier to write a query to select what you wantRiggsFolly
Also if you want subcategories and sub-subcategories of root 23 it would be useful to see at least the root category 23 and its subcategories and also its sub-subsctegories. For us to help you, you have to help usRiggsFolly

1 Answers

0
votes

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>';
}