我会用 a 封装迭代,RecursiveIterator
这样你就可以轻松地创建你想要的任何输出。
class RecursiveMenuIterator implements RecursiveIterator {
private $_data;
private $_root;
private $_position = 0;
public function __construct(array $data, $root_id = 0) {
$this->_data = $data;
$this->_root = $root_id;
}
public function valid() {
return isset($this->_data[$this->_root][$this->_position]);
}
public function hasChildren() {
$subid = $this->_data[$this->_root][$this->_position]['id'];
return isset($this->_data[$subid])
&& is_array($this->_data[$subid]);
}
public function next() {
$this->_position++;
}
public function current() {
return $this->_data[$this->_root][$this->_position];
}
public function getChildren() {
return new self($this->_data,
$this->_data[$this->_root][$this->_position]['id']);
}
public function rewind() {
$this->_position = 0;
}
public function key() {
return $this->_position;
}
public static function createFromSelect($select) {
$menu_array = array();
foreach($select->query()->fetchAll() as $row) {
$menu_array[$row['parent_id']][] = $row;
}
return new self($menu_array);
}
}
您可以使用它来创建 XML:
function iterator_to_xml($iterator, $element) {
foreach($iterator as $child) {
$childElem = $element->addChild($child['title']);
foreach($child as $key => $val) {
$childElem->addAttribute($key, $val);
}
if($iterator->hasChildren()) {
iterator_to_xml($iterator->getChildren(), $childElem);
}
}
}
或Zend_Navigation
:
function iterator_to_navigation($iterator, $container) {
foreach($iterator as $child) {
$child['label'] = $child['title'];
$page = new Zend_Navigation_Page_Uri($child);
$container->addPage($page);
if($iterator->hasChildren()) {
iterator_to_navigation($iterator->getChildren(), $page);
}
}
}
用法:
$select = $db->select()
->from("tblMenu");
$menuIterator = RecursiveMenuIterator::createFromSelect($select);
$navi = new Zend_Navigation();
iterator_to_navigation($menuIterator, $navi);
$xml = new SimpleXMLElement("<menu/>");
iterator_to_xml($menuIterator, $xml);