简体   繁体   English

从带有嵌套数据结构的平面数组中获取所有子项

[英]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. 所有类别都有ID,Parent_id和Name。

The root categories have Parent_id equal to null. 根类别的Parent_id等于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>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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