0

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

4

2 回答 2

0

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

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

于 2011-04-29T14:14:42.387 回答
0

它的基本原理...跟踪深度,并打印出<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。

于 2011-04-29T13:34:17.237 回答