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

その基本は...深さを追跡し、出力し<ul></ul>タグを付けて、深さを現在の深さに近づけます。HTML はタグを必要としないので、</li>作業が楽になることを覚えておいてください。各項目の前にa を印刷して、<li>必要に応じて要素を閉じることができます。

リストの詳細については、構造によって異なります (この編集の時点では、共有する必要はありませんでした)。ただし、このようなリストを構成するために考えられる賢明な方法が 2 つあります。

$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 に答える