0

次のような配列からツリーを作成しようとしています:

array('admin/home', 'admin/home/page', 'admin/test', 'team/tree/template', 'site');

または、より視覚的に次のように表示されます。

管理者/ホーム

管理者/ホーム/ページ

管理者/テスト

チーム/ツリー/テンプレート

サイト

ただし、各配列の最後のネストされた文字列を太字にして、それ自体が Web ページであることを示す必要もあります。

最終製品は次のようになります。

    管理
        ホームページ
            
        テスト
    チーム
        木
            テンプレート
    サイト

このサイトのいくつかの異なるソリューションを使用しましたが、正しい結果を得ることができませんでした.

どこから始めるべきかについてのアイデアや例は大歓迎です、ありがとう。

4

1 に答える 1

1

あなたはおそらく次のようなものを探しています:

<?php

$items = array('admin/home', 'admin/home/page', 'admin/test', 'site', 'team/tree/template');
sort($items);

$previous = array();
foreach ($items as $item) {
    $path = explode('/', $item);

    // $i is common nesting level of the previous item
    // e.g. 0 is nothing in common, 1 is one level in common, etc.
    for ($i = 0; $i < min(count($path), count($previous)) && ($path[$i] == $previous[$i]); $i++) { }

    // close <ul> from previous nesting levels:
    // that is, we close the amount of levels that the previous and this one have NOT in common
    for ($k = 0; $k < count($previous)-$i-1; $k++) { echo "</ul>"; }
    // $j is the current nesting level
    // we start at the common nesting level
    for ($j = $i; $j < count($path); $j++) {
        // open <ul> for new nesting levels:
        // i.e., we open a level for every level deeper than the previous level
        if ($j >= count($previous))
            echo "<ul>";
        echo "<li>";
        // make the path bold if the end of the current path is reached
        if (count($path)-1 == $j)
            echo "<b>" . $path[$j] . "</b>";
        else
            echo $path[$j];
        echo "</li>";
    }
    $previous = $path;
}
// close remaining <ul>
for ($k = 0; $k < count($previous); $k++) { echo "</ul>"; }
?>

ネストされたすべてのアイテムが隣り合うように配列を並べ替えていることに注意してください。

バグがあるかもしれませんが、自分で解決できると思います。ネストされた を開く前にリスト項目を閉じることに注意してください<ul>。これは実際にはそうあるべきではありません。実際には、そのレベルで<ul>最終的にネストされたものを開く必要があると思いますが、それは自分で理解できます。<li>

更新<ul>場合によっては を適切に閉じるようにコードを更新しました。

于 2012-06-03T19:17:19.837 に答える