【问题标题】:Get all children items from flat array with nested data structure使用嵌套数据结构从平面数组中获取所有子项
【发布时间】:2015-12-12 02:38:02
【问题描述】:

我有一组平面类别。所有类别都有 ID、Parent_id 和 Name。

根类别的 Parent_id 等于 null。它们具有可能将它们作为父级的子类别,并且它们可能是具有作为父级的子类别的子子类别。 (他们可能有很多级别)。 我可以通过单个查询将所有类别放入一个平面数组中。我需要的是 - 如果我采用一个类别(或一个子类别),我如何获得该类别中包含的所有嵌套类别(子类别、子子类别)的列表?遇到了这个问题:(

数组如下所示:

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] => 
    )

【问题讨论】:

  • 你想给我们一个视觉线索关于这个数组是什么样子的吗,然后还有一个你想要的结果的例子。否则人们只会忽略这个问题。看看the perfect question
  • 我觉得写一个查询来选择你想要的东西会更容易
  • 此外,如果您想要根 23 的子类别和子子类别,那么至少查看根类别 23 及其子类别及其子子类别会很有用。为了我们帮助你,你必须帮助我们

标签: php arrays tree


【解决方案1】:

您可以使用递归。它看起来像这样:

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

【讨论】:

  • 我不需要以 HTML 格式输出。就像给了我一个根类别 23,我怎样才能获得 23 的所有子类别和子类别的列表。
  • 致电outTree($tree, 23)
  • 我提出了这个想法。你可以修改函数来达到想要的效果。
猜你喜欢
  • 2016-06-13
  • 2015-08-04
  • 2013-02-04
  • 1970-01-01
  • 2011-06-26
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多