2012-09-22 24 views
0

我有DB。我使用Zend導航來生成菜單。但我希望我的菜單可以從面板動態編輯。我的菜單也有子菜單。Mysql菜單到xml

我的DB:

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> 

如何從數據庫生成XML這將看起來像我寫的嗎?

+0

我看到一個遞歸函數和一些[ XML-fu](http://php.net/manual/en/book.simplexml.php)來你的辦法。 – vstm

+0

你能舉一些例子嗎? – beetle

+0

那麼,你需要XML還是你真的只需要你的'Zend_Navigation'容器中的數據庫數據? – vstm

回答

0

我會用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);