douchuifk90315 2015-12-11 18:03
浏览 46

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

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条回答 默认 最新

  • duancong2160 2015-12-11 18:38
    关注

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法