【问题标题】:How can I build a nested HTML list with an infinite depth from a flat array?如何从平面数组构建具有无限深度的嵌套 HTML 列表?
【发布时间】:2012-02-10 07:27:12
【问题描述】:

我正在尝试从格式如下的源数组生成多级 HTML 列表:

/**
 * id = unique id
 * parent_id = "id" that this item is directly nested under
 * text = the output string
 */
$list = array(
    array(
        'id'        =>  1,
        'parent_id' =>  0,
        'text'      =>  'Level 1',
    ), array(
        'id'        =>  2,
        'parent_id' =>  0,
        'text'      =>  'Level 2',
    ), array(
        'id'        =>  3,
        'parent_id' =>  2,
        'text'      =>  'Level 2.1',
    ), array(
        'id'        =>  4,
        'parent_id' =>  2,
        'text'      =>  'Level 2.2',
    ), array(
        'id'        =>  5,
        'parent_id' =>  4,
        'text'      =>  'Level 2.2.1',
    ), array(
        'id'        =>  6,
        'parent_id' =>  0,
        'text'      =>  'Level 3',
    )
);

目标是具有无限深度的嵌套<ul>。上面数组的预期输出是这样的:

  • 1 级
  • 2级
    • 2.1 级
    • 2.2级
      • 2.2.1级
  • 3 级

如果只有数组项有一个名为 child 的键或包含实际子数组的东西,那么很容易通过这些进行递归并使用如下函数获得所需的输出:

function makeList($list)
{
    echo '<ul>';
    foreach ($list as $item)
    {
        echo '<li>'.$item['text'];
        if (isset($item['child']))
        {
            makeList($item['child']);
        }
        echo '</li>';
    }
    echo '</ul>';
}

不幸的是,我的情况并非如此 - 源数组的格式无法更改。所以,很久以前我写了这个非常讨厌的函数来实现它,它最多只能工作三个级别(代码是用原始 cmets 逐字粘贴的)。我知道这是一个很无聊的阅读,请多多包涵:

function makeArray($links)
{
    // Output
    $nav = array();

    foreach ($links as $k => $v)
    {
        // If no parent_id is present, we can assume it is a top-level link
        if (empty($v['parent_id']))
        {
            $id = isset($v['id']) ? $v['id'] : $k;

            $nav[$id] = $v;

            // Remove from original array
            unset($links[$k]);
        }
    }

    // Loop through the remaining links again,
    // we can assume they all have a parent_id
    foreach ($links as $k => $v)
    {
        // Link's parent_id is in the top level array, so this is a level-2 link
        // We already looped through every item so we know they are all accounted for
        if (isset($nav[$v['parent_id']]))
        {
            $id = isset($v['id']) ? $v['id'] : $k;

            // Add it to the top level links as a child
            $nav[$v['parent_id']]['child'][$id] = $v;

            // Set a marker so we know which ones to loop through to add the third level
            $nav2[$id] = $v;

            // Remove it from the array
            unset($links[$k]);
        }
    }

    // Last iteration for the third level
    // All other links have been removed from the original array at this point
    foreach ($links as $k => $v)
    {
        $id = isset($v['id']) ? $v['id'] : $k;

        // Link's parent_id is in the second level array, so this is a level-3 link
        // Orphans will be ignored
        if (isset($nav2[$v['parent_id']]))
        {
            // This part is crazy, just go with it
            $nav3 = $nav2[$v['parent_id']]['parent_id'];
            $nav[$nav3]['child'][$v['parent_id']]['child'][] = $v;
        }

    }

    return $nav;
}

这使得数组如下:

array(
    'text' => 'Level 1'
    'child' => array(
        array(
            'text' => 'Level 1.2'
            'child' => array(
                array(
                    'text' => 'Level 1.2.1'
                    'child' => array(
                        // etc.
                   ),
                array(
                    'text' => 'Level 1.2.2'
                    'child' => array(
                        // etc.
                   ),
                )
             )
        )
    )
);

用法:

$nav = makeArray($links);
makeList($nav);

我花了很多空闲时间试图解决这个问题,我在这里给出的原始代码仍然是我能够产生的最佳解决方案。

如果没有那个糟糕的功能(深度限制为 3),我怎么能做到这一点,并且有无限数量的关卡?有没有更优雅的解决方案?

【问题讨论】:

    标签: php recursion


    【解决方案1】:

    打印:

    function printListRecursive(&$list,$parent=0){
        $foundSome = false;
        for( $i=0,$c=count($list);$i<$c;$i++ ){
            if( $list[$i]['parent_id']==$parent ){
                if( $foundSome==false ){
                    echo '<ul>';
                    $foundSome = true;
                }
                echo '<li>'.$list[$i]['text'].'</li>';
                printListRecursive($list,$list[$i]['id']);
            }
        }
        if( $foundSome ){
            echo '</ul>';
        }
    }
    
    printListRecursive($list);
    

    创建多维数组:

    function makeListRecursive(&$list,$parent=0){
        $result = array();
        for( $i=0,$c=count($list);$i<$c;$i++ ){
            if( $list[$i]['parent_id']==$parent ){
                $list[$i]['childs'] = makeListRecursive($list,$list[$i]['id']);
                $result[] = $list[$i];
            }
        }
        return $result;
    }
    
    $result = array();
    $result = makeListRecursive($list);
    echo '<pre>';
    var_dump($result);
    echo '</pre>';
    

    【讨论】:

    • 这也很好用,谢谢。我选择了 Joe 的方法,因为它的代码更少。
    • 实际上,当数组的顺序不同时,另一个有效的答案失败了,而这个有效。
    【解决方案2】:

    测试和工作:)

    $list = array(...);
    $nested = array();
    
    foreach ($list as $item)
    {
        if ($item['parent_id'] == 0)
        {
            // Woot, easy - top level
            $nested[$item['id']] = $item;
        }
        else
        {
            // Not top level, find it's place
            process($item, $nested);
        }
    }
    
    // Recursive function
    function process($item, &$arr)
    {
        if (is_array($arr))
        {
            foreach ($arr as $key => $parent_item)
            {
                // Match?
                if (isset($parent_item['id']) && $parent_item['id'] == $item['parent_id'])
                {
                    $arr[$key]['children'][$item['id']] = $item;
                }
                else
                {
                    // Keep looking, recursively
                    process($item, $arr[$key]);
                }
            }
        }
    }
    

    【讨论】:

    • 在您的第一篇文章的顶部是带有$list = array(... 的代码块 - 将其复制到我的代码中,覆盖第一行:$list = array(...); - 现在,在foreach() 之后,执行@ 987654325@ 看看你有什么:) 它应该很容易插入makeList。嗯,你的评论被删除了。无论如何我都会把它留在这里:)
    • 我希望它现在在这里更活跃,你应该得到更多的代表。我早上回来给你打勾。
    • 刚刚创建了 30 个帐户,在他们身上种植您需要的代表,然后投票给我:P Simples。
    • 实际上,我又回来处理这个问题,它非常依赖于数组的特定顺序,例如rsort($list) 会导致它不起作用。
    • 嗯,很抱歉打扰您 - 给出的数组只是一个示例,实际的源数组可能有不同的顺序。听起来你明白我的目的。无论哪种方式,我仍然感谢帮助和代码。
    【解决方案3】:

    我最近写的一些方法,也许有些会有所帮助,对不起,我时间紧迫,无法重写它们以满足您的需求。

    这段代码实际上是Kohana Framework Model的一部分,方法-&gt;as_array()用于扁平化一个Database_Result对象。

    function array_tree($all_nodes){
        $tree = array();
        foreach($all_nodes as $node){
            $tree[$node->id]['fields'] = $node->as_array();
            $tree[$node->id]['children'] = array();
    
            if($node->parent_id){
                 $tree[$node->parent_id]['children'][$node->id] =& $tree[$node->id];
            }
        }
    
    
        $return_tree = array();
        foreach($tree as $node){
            if($node['fields']['depth'] == 0){
                $return_tree[$node['fields']['id']] = $node;
            }
        }
    
        return $return_tree;
    }
    

    array_tree() 用于从平面数组中生成一棵树。关键特性是=&amp; 部分;)

    function html_tree($tree_array = null){
            if( ! $tree_array){
               $tree_array = $this -> array_tree();
            }
    
            $html_tree = '<ul>'."\n";
            foreach($tree_array as $node){
                $html_tree .= $this->html_tree_crawl($node);
            }
            $html_tree .= '</ul>'."\n";
    
    
            return $html_tree;
        }
    
    function html_tree_crawl($node){
            $children = null;
    
            if(count($node['children']) > 0){
                $children = '<ul>'."\n";
                foreach($node['children'] as $chnode){
                    $children .= $this->html_tree_crawl($chnode);
                }
                $children .= '</ul>'."\n";
            }
    
            return $this->html_tree_node($node, $children);
        }
    

    html_tree_node() 是一种在 HTML 中显示当前节点和子节点的简单方法。 示例如下:

    <li id="node-<?= $node['id'] ?>">
        <a href="#"><?= $node['title'] ?></a>
        <?= (isset($children) && $children != null) ? $children : '' ?>
    </li>
    

    【讨论】:

    • 在挖掘了 Kohana 源代码之后,我始终没有弄清楚如何将这些拼凑起来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多