用RecursiveIteratorIterator类来实现,详见代码:
PHP代码
- <?php header('Content-Type: text/html; charset=utf-8');?>
- <style>
- ul {list-style-type: circle}
- </style>
- <?php
- $array = array(
- "苹果" => array (
- "一代" => array(
- "苹果1", "苹果1S"
- ),
- "二代" => array(
- "苹果2", array(
- "苹果2 8G","苹果2 16G"
- ),
- ),
- "三代" => array()
- ),
- "三星" => array(
- "galaxy S4", "galaxy S5"
- ),
- );
- class RecursiveListIterator extends RecursiveIteratorIterator {
- public $tab = " ";
- public function beginChildren() {
- if (count($this->getInnerIterator()) == 0) { return; }
- echo str_repeat($this->tab, $this->getDepth()), "<ul>
"; - }
- public function endChildren() {
- if (count($this->getInnerIterator()) == 0) { return; }
- echo str_repeat($this->tab, $this->getDepth()), "</ul>
"; - echo str_repeat($this->tab, $this->getDepth()), "</li>
"; - }
- public function nextElement() {
- // 显示叶子节点
- if ( ! $this->callHasChildren()) {
- echo str_repeat($this->tab, $this->getDepth()+1), '<li>', $this->current(), "</li>
"; - return;
- }
- // 显示分支标签
- echo str_repeat($this->tab, $this->getDepth()+1), '<li>', $this->key();
- echo (count($this->callGetChildren()) == 0) ? "</li>
" : "
"; - }
- }
- $it = new RecursiveListIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST); &