0

我有数据库。我使用 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>

 <sub_first_2>
 </sub_first_2>

</first>

如何从 DB 生成看起来像我写的那个的 xml?

4

1 回答 1

0

我会用 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);
于 2012-09-22T19:38:27.397 回答