【问题标题】:php html display hierarchical dataphp html 显示分层数据
【发布时间】:2015-12-26 19:00:05
【问题描述】:

我有一个数组 ($title, $depth)

$title($depth)
////////////////////////////////////
ELECTRONICS(0)
    TELEVISIONS(1)
        TUBE(2)
        LCD(2)
        PLASMA(2)
    PORTABLE ELECTRONICS(1)
        MP3 PLAYERS(2)
            FLASH(3)
        CD PLAYERS(2)
        2 WAY RADIOS(2)
//////////////////////

我怎样才能用<ul><li>显示这个结构

【问题讨论】:

  • 您的问题到底是什么?你坚持这样做的哪个方面?
  • 你的实际数组是什么样子的,你能给我们看看print_rvar_dump吗?
  • 我想用这个创建垂直菜单
  • 但是您的数据是什么样的?
  • 您的问题到底是什么?你坚持这样做的哪个方面?

标签: php html hierarchical


【解决方案1】:

它的基本原理...跟踪深度,并打印出<ul></ul> 标签以将深度推向当前深度。请记住,HTML 不需要</li> 标签,它让生活更轻松。您可以在每个项目之前打印出<li>,然后让元素根据需要自行关闭。

现在,至于查看列表的具体细节,这取决于结构(在本次编辑时,您还不想分享)。不过,我可以想到两种合理的方式来构建这样的列表。

$depth = -1;
// May be foreach($arr as $title => $itemDepth), depending on the structure
foreach ($arr as $item)
{
    // if you did the 'other' foreach, get rid of this
    list($title, $itemDepth) = $item;

    // Note, this only works decently if the depth increases by
    // at most one level each time.  The code won't work if you
    // suddenly jump from 1 to 5 (the intervening <li>s won't be
    // generated), so there's no sense in pretending to cover that
    // case with a `while` or `str_repeat`.
    if ($depth < $itemDepth)
        echo '<ul>';
    elseif ($depth > $itemDepth)
        echo str_repeat('</ul>', $depth - $itemDepth);

    echo '<li>', htmlentities($title);
    $depth = $itemDepth;
}

echo str_repeat('</ul>', $depth + 1);

这不会生成有效的 XHTML。但无论如何,大多数人不应该使用 XHTML。

【讨论】:

    【解决方案2】:

    您可以使用这样的递归函数。

    $data = array(
        'electronics' => array(
            'televisions' => array(
                'tube',
                'lcd',
                'plasma',
            ),
            'portable electronics' => array(
                'MP3 players' => array(
                    'flash',
                ),
                'CD players',
                '2 way radios',
            ),
        ),
    );
    
    function build_ul($contents){
        $list = "<ul>\n";
    
        foreach($contents as $index => $value){
            if(is_array($value)){
                $item = "$index\n" . build_ul($value);
            } else {
                $item = $value;
            }
           $list .= "\t<li>$item</li>\n";
        }
    
        $list .= "</ul>\n";
    
        return $list;
    }
    
    
    print build_ul($data);
    

    您必须修改函数才能添加显示类别总数的数字。

    请注意,由于 PHP 没有像其他一些语言(例如 Lisp)那样针对处理递归函数进行优化,因此如果您有大量数据,您可能会遇到性能问题。另一方面,如果你的层次结构比三或四层次更深,你就会开始遇到问题,因为很难在一个网页中合理地显示这么多层次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多