Php Mysql菜单到xml
我有DB。我使用Zend Navigation生成菜单。但我希望我的菜单可以从面板中动态编辑。我的菜单也有子菜单 我的数据库:Php Mysql菜单到xml,php,zend-framework,Php,Zend Framework,我有DB。我使用Zend Navigation生成菜单。但我希望我的菜单可以从面板中动态编辑。我的菜单也有子菜单 我的数据库: id title parent 1 First 0 2 sub_first 1 3. sub_first_2 1 4. second 0 5. sub_second 4 我希望以这种方式将其导出为XML: <first> <sub_first> </sub_first>
id title parent
1 First 0
2 sub_first 1
3. sub_first_2 1
4. second 0
5. sub_second 4
我希望以这种方式将其导出为XML:
<first>
<sub_first>
</sub_first>
<sub_first_2>
</sub_first_2>
</first>
如何从DB生成xml,它看起来就像我写的那样?我会用一个
递归迭代器来封装迭代,这样你就可以轻松地创建你想要的任何输出
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_导航
:
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);
$select=$db->select()
->来自(“tblMenu”);
$menuIterator=RecursiveMenuIterator::createFromSelect($select);
$navi=新Zend_导航();
迭代器到导航($menuIterator,$navi);
$xml=新的SimpleXMLElement(“”);
迭代器到xml($menuIterator,$xml);
我看到一个递归函数和一些即将出现的函数。那么,您是需要XML还是真的只需要Zend_Navigation
-容器中的DB数据?我需要XML-但我仍然无法处理(我无法编写正确的算法)。但我知道如何将DB连接到Zend_导航,但我有多个子菜单,所以我决定使用XML。对吗?你会在我的位置上做什么?