我无法理解RecrusiveIteratorIterator
和亲戚迭代多维页面数组以在PHP中构建多级菜单。
通常我只是创建一个循环遍历某个级别的函数,并调用自身循环遍历任何子级。但是我想利用PHP中的迭代器接口来改进我的代码。
我的数组看起来像这样:
$pages = array(
new Page(1, 'Home'),
new Page(2, 'Pages', array(
new Page(3, 'About'),
new Page(4, 'Contact')
)),
new Page(5, 'Categories', array(
new Page(6, 'Clothing'),
new Page(7, 'DVDs')
))
);
我的Page
构造函数中的参数只是页面ID和页面名称。
如何使用PHP的迭代器构建一个看起来像这样的菜单?
<ul>
<li>Home</li>
<li>Pages
<ul>
<li>About</li>
<li>Contact</li>
</ul>
</li>
<li>Categories
<ul>
<li>Clothing</li>
<li>DVDs</li>
</ul>
</li>
</ul>
答案 0 :(得分:1)
这通常是一个三步程序:
RecursiveIterator
,它为您的树结构提供递归迭代。看起来RecursiveArrayIterator
符合您的需求。RecursiveIteratorIterator
对其进行迭代,以便将回归转换为您的输出(与RecursiveTreeIterator
进行比较)。foreach
与更具体的RecursiveIteratorIterator
进行迭代来完成输出。代码示例:
// consume implementation of step 1
$it = new PagesRecursiveIterator($pages);
// consume implementation of step 2
$list = new RecursiveUlLiIterator($it);
// perform iteration given in step 3
foreach($list as $page) {
echo $page->getName();
}