divil666
Новичок
Оцените класс для прохода по дереву в виде одномерного массива
Мне в первую очередь интересна критика и мнение людей.
В общем дело связано с Doctrine и возвратом ею дерева из базы данных в виде обычного одномерного массива (сортировка осуществляется по cleft полю).
Написанный мною класс позволяет проходится по массиву используя стандартный интерфейс RecursiveIterator.
Подобное может пригодиться при отображении дерева используя RecursiveIteratorIterator.
Мне в первую очередь интересна критика и мнение людей.
В общем дело связано с Doctrine и возвратом ею дерева из базы данных в виде обычного одномерного массива (сортировка осуществляется по cleft полю).
Написанный мною класс позволяет проходится по массиву используя стандартный интерфейс RecursiveIterator.
Подобное может пригодиться при отображении дерева используя RecursiveIteratorIterator.
PHP:
/**
*
* @author divil666
*
*/
class Nable_DoctrineNestedSetArrayIterator implements RecursiveIterator
{
protected $_treeArray;
protected $_current;
protected $_currentLevel;
protected $_lastChildEnd;
public function __construct(Array $treeArray)
{
$this->_treeArray = $treeArray;
$this->_current = 0;
$this->_currentLevel = $this->_treeArray[0]['level'];
$this->_lastChildEnd = 0;
}
public function rewind()
{
$this->_current = 0;
}
public function next()
{
$this->_current++;
}
public function current()
{
return $this->_treeArray[$this->_current];
}
public function key()
{
return $this->_treeArray[$this->_current]['id'];
}
public function valid()
{
if (isset($this->_treeArray[$this->_current])) {
if ($this->_treeArray[$this->_current]['level'] === $this->_currentLevel) {
return true;
} elseif (isset($this->_treeArray[$this->_lastChildEnd])) {
$this->_current = $this->_lastChildEnd;
return true;
}
}
return false;
}
public function hasChildren()
{
$current = $this->current();
return ($current['rgt'] > ($current['lft'] + 1));
}
public function getChildren()
{
$childrens = array();
$currentLevel = $this->_treeArray[$this->_current]['level'];
for ($i = $this->_current + 1; isset($this->_treeArray[$i])
&& $this->_treeArray[$i]['level'] > $currentLevel; $i++) {
$childrens[] = $this->_treeArray[$i];
}
$this->_lastChildEnd = $i;
return new self($childrens);
}
}
