PHP HTML显示分层数据


php html display hierarchical data

我有一个数组($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>

显示这个结构?

它的基础…跟踪深度,并打印出<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

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

$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)那样针对处理递归函数进行优化,因此如果您有大量数据,可能会遇到性能问题。另一方面,如果你的层次结构比三层或四层更深,你无论如何都会遇到问题,因为很难在单个网页中合理地显示那么多层次结构。