另一种更简化的方式将$tree
中的扁平结构转换为层次结构。仅需要一个临时数组揭露它:
// add children to parents
$flat = array(); # temporary array
foreach ($tree as $name => $parent)
{
$flat[$name]['name'] = $name; # self
if (NULL === $parent)
{
# no parent, is root element, assign it to $tree
$tree = &$flat[$name];
}
else
{
# has parent, add self as child
$flat[$parent]['children'][] = &$flat[$name];
}
}
unset($flat);
这是所有获得的层次结构成多维数组:
Array
(
[children] => Array
(
[0] => Array
(
[children] => Array
(
[0] => Array
(
[name] => H
)
[1] => Array
(
[name] => F
)
)
[name] => G
)
[1] => Array
(
[name] => E
[children] => Array
(
[0] => Array
(
[name] => A
)
[1] => Array
(
[children] => Array
(
[0] => Array
(
[name] => B
)
)
[name] => C
)
)
)
)
[name] => D
)
输出是,如果你想避免递归少微不足道(可能是一个大结构的负担)。
我一直想解决输出数组的UL/LI“难题”。困境是,每个项目都不知道孩子是否会跟进或需要关闭多少前面的元素。在另一个答案我已经解决了,通过使用RecursiveIteratorIterator
并寻找getDepth()
和我自己写的Iterator
提供的其他元信息:Getting nested set model into a <ul>
but hiding “closed” subtrees。 answer显示,与迭代器,你很灵活。
但是这是一个预先排序的列表,所以不适合您的示例。此外,我一直想解决这个问题的一种标准树结构和HTML的<ul>
和<li>
元素。
我想出的基本概念是:
TreeNode
- 文摘每个元素成简单TreeNode
类型,可以提供它的值(例如Name
),以及是否有孩子。
TreeNodesIterator
- A RecursiveIterator
能够遍历这些TreeNodes
的集合(数组)。这很简单,因为TreeNode
类型已经知道它是否有孩子和哪些孩子。
RecursiveListIterator
- 有当递归遍历任何一种RecursiveIterator
所需的所有事件RecursiveIteratorIterator
:
beginIteration
/endIteration
- 开始和主列表的末尾。
beginElement
/endElement
- 每个元素的开始和结束。
beginChildren
/endChildren
- 每个子列表的开始和结束。 这个RecursiveListIterator
只以函数调用的形式提供这些事件。儿童名单,因为它是典型的<ul><li>
名单,被打开和关闭它的父母<li>
元素。因此endElement
事件在相应的endChildren
事件之后被触发。这可以改变或可配置,以扩大使用这个类。这些事件是作为函数调用分发给装饰器对象的,然后将事情分开。
ListDecorator
- A “装饰” 类,它仅仅是一个RecursiveListIterator
事件的接收器。
我从主输出逻辑开始。两者现在分层$tree
阵列,最终代码如下所示:
$root = new TreeNode($tree);
$it = new TreeNodesIterator(array($root));
$rit = new RecursiveListIterator($it);
$decor = new ListDecorator($rit);
$rit->addDecorator($decor);
foreach($rit as $item)
{
$inset = $decor->inset(1);
printf("%s%s\n", $inset, $item->getName());
}
首先,让我们看看,简单地包装了<ul>
和<li>
元素,并在判决的表结构如何输出的ListDecorator
:
class ListDecorator
{
private $iterator;
public function __construct(RecursiveListIterator $iterator)
{
$this->iterator = $iterator;
}
public function inset($add = 0)
{
return str_repeat(' ', $this->iterator->getDepth()*2+$add);
}
构造函数接受它正在处理的列表迭代器。 inset
只是输出的很好缩进的帮助函数。剩下的只是每个事件的输出功能:
public function beginElement()
{
printf("%s<li>\n", $this->inset());
}
public function endElement()
{
printf("%s</li>\n", $this->inset());
}
public function beginChildren()
{
printf("%s<ul>\n", $this->inset(-1));
}
public function endChildren()
{
printf("%s</ul>\n", $this->inset(-1));
}
public function beginIteration()
{
printf("%s<ul>\n", $this->inset());
}
public function endIteration()
{
printf("%s</ul>\n", $this->inset());
}
}
考虑到这些输出功能,这是主要的输出总结/再循环,我通过它一步一步:
$root = new TreeNode($tree);
创建一个将被用于在开始迭代根TreeNode
:
$it = new TreeNodesIterator(array($root));
这TreeNodesIterator
是RecursiveIterator
,使递归迭代过第e单一$root
节点。它作为一个数组传递,因为该类需要迭代并允许与一组子元素重用,这也是一个元素数组。
$rit = new RecursiveListIterator($it);
这RecursiveListIterator
是RecursiveIteratorIterator
提供上述事件。为了利用它,可以仅设置一个ListDecorator
需要(上面的类),并分配有addDecorator
:
$decor = new ListDecorator($rit);
$rit->addDecorator($decor);
然后所有设置,使其仅foreach
于其上,并输出每个节点:
foreach($rit as $item)
{
$inset = $decor->inset(1);
printf("%s%s\n", $inset, $item->getName());
}
如本例所示,整个输出逻辑封装在ListDecorator
类和此单个foreach
中。整个递归遍历已被完全封装成提供堆栈过程的SPL递归迭代器,这意味着在内部不会进行递归函数调用。
基于事件的ListDecorator
允许您专门修改输出并为同一数据结构提供多种类型的列表。甚至可以在阵列数据已被封装到TreeNode
中时更改输入。
的完整代码例如:
<?php
namespace My;
$tree = array('H' => 'G', 'F' => 'G', 'G' => 'D', 'E' => 'D', 'A' => 'E', 'B' => 'C', 'C' => 'E', 'D' => null);
// add children to parents
$flat = array(); # temporary array
foreach ($tree as $name => $parent)
{
$flat[$name]['name'] = $name; # self
if (NULL === $parent)
{
# no parent, is root element, assign it to $tree
$tree = &$flat[$name];
}
else
{
# has parent, add self as child
$flat[$parent]['children'][] = &$flat[$name];
}
}
unset($flat);
class TreeNode
{
protected $data;
public function __construct(array $element)
{
if (!isset($element['name']))
throw new InvalidArgumentException('Element has no name.');
if (isset($element['children']) && !is_array($element['children']))
throw new InvalidArgumentException('Element has invalid children.');
$this->data = $element;
}
public function getName()
{
return $this->data['name'];
}
public function hasChildren()
{
return isset($this->data['children']) && count($this->data['children']);
}
/**
* @return array of child TreeNode elements
*/
public function getChildren()
{
$children = $this->hasChildren() ? $this->data['children'] : array();
$class = get_called_class();
foreach($children as &$element)
{
$element = new $class($element);
}
unset($element);
return $children;
}
}
class TreeNodesIterator implements \RecursiveIterator
{
private $nodes;
public function __construct(array $nodes)
{
$this->nodes = new \ArrayIterator($nodes);
}
public function getInnerIterator()
{
return $this->nodes;
}
public function getChildren()
{
return new TreeNodesIterator($this->nodes->current()->getChildren());
}
public function hasChildren()
{
return $this->nodes->current()->hasChildren();
}
public function rewind()
{
$this->nodes->rewind();
}
public function valid()
{
return $this->nodes->valid();
}
public function current()
{
return $this->nodes->current();
}
public function key()
{
return $this->nodes->key();
}
public function next()
{
return $this->nodes->next();
}
}
class RecursiveListIterator extends \RecursiveIteratorIterator
{
private $elements;
/**
* @var ListDecorator
*/
private $decorator;
public function addDecorator(ListDecorator $decorator)
{
$this->decorator = $decorator;
}
public function __construct($iterator, $mode = \RecursiveIteratorIterator::SELF_FIRST, $flags = 0)
{
parent::__construct($iterator, $mode, $flags);
}
private function event($name)
{
// event debug code: printf("--- %'.-20s --- (Depth: %d, Element: %d)\n", $name, $this->getDepth(), @$this->elements[$this->getDepth()]);
$callback = array($this->decorator, $name);
is_callable($callback) && call_user_func($callback);
}
public function beginElement()
{
$this->event('beginElement');
}
public function beginChildren()
{
$this->event('beginChildren');
}
public function endChildren()
{
$this->testEndElement();
$this->event('endChildren');
}
private function testEndElement($depthOffset = 0)
{
$depth = $this->getDepth() + $depthOffset;
isset($this->elements[$depth]) || $this->elements[$depth] = 0;
$this->elements[$depth] && $this->event('endElement');
}
public function nextElement()
{
$this->testEndElement();
$this->event('{nextElement}');
$this->event('beginElement');
$this->elements[$this->getDepth()] = 1;
}
public function beginIteration()
{
$this->event('beginIteration');
}
public function endIteration()
{
$this->testEndElement();
$this->event('endIteration');
}
}
class ListDecorator
{
private $iterator;
public function __construct(RecursiveListIterator $iterator)
{
$this->iterator = $iterator;
}
public function inset($add = 0)
{
return str_repeat(' ', $this->iterator->getDepth()*2+$add);
}
public function beginElement()
{
printf("%s<li>\n", $this->inset(1));
}
public function endElement()
{
printf("%s</li>\n", $this->inset(1));
}
public function beginChildren()
{
printf("%s<ul>\n", $this->inset());
}
public function endChildren()
{
printf("%s</ul>\n", $this->inset());
}
public function beginIteration()
{
printf("%s<ul>\n", $this->inset());
}
public function endIteration()
{
printf("%s</ul>\n", $this->inset());
}
}
$root = new TreeNode($tree);
$it = new TreeNodesIterator(array($root));
$rit = new RecursiveListIterator($it);
$decor = new ListDecorator($rit);
$rit->addDecorator($decor);
foreach($rit as $item)
{
$inset = $decor->inset(2);
printf("%s%s\n", $inset, $item->getName());
}
Outpupt:
<ul>
<li>
D
<ul>
<li>
G
<ul>
<li>
H
</li>
<li>
F
</li>
</ul>
</li>
<li>
E
<ul>
</li>
<li>
A
</li>
<li>
C
<ul>
<li>
B
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Demo (PHP 5.2 variant)
一种可能的变体将是遍历任何RecursiveIterator
并提供对所有事件的迭代的迭代器可能发生。然后,foreach循环内的开关/情况可以处理事件。
相关:
大肚。我怎样才能改变printTree函数不直接回应树的html,但保存所有的输出html到一个变量并返回它?谢谢 – Enrique 2012-12-17 13:58:59
嗨,我认为函数声明必须是parseAndPrintTree($ tree,$ root = null) 并且递归调用应该是parseAndPrintTree($ child,$ tree); 致以问候 – razor7 2014-04-25 20:52:02