Класс дерева на php

class Tree (Дерево)

Class Tree (Дерево) – класс для работы с древовидными структурами, оптимизирован под высокую производительность, работу с большим количеством вложенных узлов, без труда способен обработать дерево с 25000 — 30000 элементами менее чем за 1 секунду.

class Tree

/** * Установить порядок сортировки элемента по id * @param mixed $id — идентификатор элемента * @param integer $order — порядок сортировки */

public function setItemOrder( $id , $order )

/** * Отсортировать дочерние элементы * @param mixed $parentId — необязательное, идентификатор родителя, по * умолчанию корневой узел, сортирует все узлы */

public function sortItems( $parentId = false )

/** * Проверить существует ли узел по его идентификатору * @param mixed $id * @return boolean */

public function itemExists( $id )

/** * Получить количество элементов в дереве * @return integer */

public function getItemsCount()

/** * Добавить узел в дерево * @param mixed $id — уникальный идентификатор * @param mixed $parent — идентификатор родительского узла * @param mixed $data — данные узла * @param integer $order — порядок сортировки, необязательное * @return boolean — успешность выполнения */

public function addItem( $id , $parent , $data , $order = false )

/** * Обновить данные узла * @param mixed $id — идентификатор узла * @param mixed $data — данные узла * @return boolean — успешность выполнения */

public function updateItem( $id , $data )

/** * Получить структуру узла по его идентификатору * @param mixed $id * @return array массив с ключами (‘id’,’parent’,’order’,’data’) */

public function getItem( $id )

/** * Получить данные узла по его идентификатору * @param string $id * @return mixed */

public function getItemData( $id )

/** * Проверить есть ли у узла дочерние * @param string $id — идентификатор узла * @return boolean */

public function hasChilds( $id )

/** * Получить структуры всех дочерних узлов (рекурсивно) * @var mixed id идентификатор родительского узла * @return array массив с ключами (‘id’,’parent’,’order’,’data’) */

public function getChildsR( $id )

/** * Получить структуры дочерних узлов * @var mixed id — идентификатор родительского узла * @return array массив с ключами (‘id’,’parent’,’order’,’data’) */

public function getChilds( $id )

/** * Получить идентификатор родительского узла по идентификатору дочернего * @param string $id — идентификатор дочернего узла * @return mixed string or false */

Читайте также:  Interrupted by user питон

public function getParentId( $id )

/** * Сменить родительский узел для узла * @param mixed $id — идентификатор узла * @param mixed $newParent — идентификатор нового родительского узла * @return boolean */

public function changeParent( $id , $newParent )

/** * Удалить узел * @param mixed $id * @return void */

public function removeItem( $id )

/** * Получить структуры всех элементов (узлов) дерева * @return array массив с ключами (‘id’,’parent’,’order’,’data’) */

public function getItems()

Пример работы с деревом:

// функция построения узла function createNode($tree , $parent) < $s=''; if(!$tree->hasChilds($parent)) return ''; $childs = $tree->getChilds($parent); foreach ($childs as $k=>$v) < $s.='
$v['data']['code'].'">'.$v['data']['title'].'

'.$v['data']['somedata'].'

'; if($tree->hasChilds($v['id'])) $s.=createNode($tree , $v['id']); $s.='
'
; > return $s; > // подготавливаем данные $data = array( array('id'=>1,'code'=>'index','parent'=>0,'order'=>0,'title'=>'Main','somedata'=>'text 1'), array('id'=>2,'code'=>'store','parent'=>0,'order'=>1,'title'=>'Store','somedata'=>'text 2'), array('id'=>3,'code'=>'catalog','parent'=>2,'order'=>0,'title'=>'Store - Catalog','somedata'=>'text 3'), array('id'=>4,'code'=>'goods','parent'=>2,'order'=>1,'title'=>'Store - Catalog - Goods','somedata'=>'text 4'), array('id'=>5,'code'=>'price','parent'=>4,'order'=>2,'title'=>'Store - Catalog - Goods - Price','somedata'=>'text 5'), ); $tree = new Tree(); // заполняем дерево данными foreach ($data as $item) < $tree->addItem( $item['id'], $item['parent'], array( 'title'=>$item['title'] , 'code'=> $item['code'] , 'somedata'=>$item['somedata'] ), $item['order'] ); > // распечатываем дерево echo createNode($tree , 0);

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A basic but flexible tree data structure for php and a fluent tree builder implementation.

License

nicmart/Tree

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

…nit-9.6.10 composer(deps-dev): Bump phpunit/phpunit from 9.6.9 to 9.6.10

Git stats

Files

Failed to load latest commit information.

README.md

In Tree you can find a basic but flexible tree data structure for php together with and an handful Builder class, that enables you to build tree in a fluent way.

The Tree\Node\NodeInterface interface abstracts the concept of a tree node. In Tree a Node has essentially two things: a set of children (that implements the same NodeInterface interface) and a value.

On the other hand, the Tree\Node\Node gives a straight implementation for that interface.

use Tree\Node\Node; $node = new Node('foo');

Getting and setting the value of a node

Each node has a value property, that can be any php value.

$node->setValue('my value'); echo $node->getValue(); //Prints 'my value'

Adding one or more children

$child1 = new Node('child1'); $child2 = new Node('child2'); $node ->addChild($child1) ->addChild($child2);

Getting the array of all children

$children = $node->getChildren();

Overwriting the children set

$node->setChildren([new Node('foo'), new Node('bar')]);

Getting if the node is a leaf or not

A leaf is a node with no children.

Getting if the node is a child or not

A child is a node that has a parent.

Getting the parent of a node

Reference to the parent node is automatically managed by child-modifiers methods

$root->addChild($node = new Node('child')); $node->getParent(); // Returns $root

Getting the ancestors of a node

$root = (new Node('root')) ->addChild($child = new Node('child')) ->addChild($grandChild = new Node('grandchild')) ; $grandchild->getAncestors(); // Returns [$root, $child]

Getting the root of a node

Getting the neighbors of a node

$root = (new Node('root')) ->addChild($child1 = new Node('child1')) ->addChild($child2 = new Node('child2')) ->addChild($child3 = new Node('child3')) ; $child2->getNeighbors(); // Returns [$child1, $child3]

Getting the number of nodes in the tree

Getting the depth of a node

Getting the height of a node

The builder provides a convenient way to build trees. It is provided by the Builder class, but you can implement your own builder making an implementation of the BuilderInterface class.

Let’s see how to build the following tree, where the nodes label are represents nodes values:

$builder = new Tree\Builder\NodeBuilder; $builder ->value('A') ->leaf('B') ->tree('C') ->tree('D') ->leaf('G') ->leaf('H') ->end() ->leaf('E') ->leaf('F') ->end() ; $nodeA = $builder->getNode();

The example should be self-explanatory, but here you are a brief description of the methods used above.

Set the value of the current node to $value

Add to the current node a new child whose value is $value .

Add to the current node a new child whose value is $value , and set the new node as the builder current node.

Returns to the context the builder was before the call to tree method, i.e. make the builder go one level up.

You can obtain the yield of a tree (i.e. the list of leaves in a pre-order traversal) using the YieldVisitor.

For example, if $node is the tree built above, then

use Tree\Visitor\YieldVisitor; $visitor = new YieldVisitor; $yield = $node->accept($visitor); // $yield will contain nodes B, G, H, E, F

You can walk a tree in pre-order:

use Tree\Visitor\PreOrderVisitor; $visitor = new PreOrderVisitor; $yield = $node->accept($visitor); // $yield will contain nodes A, B, C, D, G, H, E, F

You can walk a tree in post-order:

use Tree\Visitor\PostOrderVisitor; $visitor = new PostOrderVisitor; $yield = $node->accept($visitor); // $yield will contain nodes B, G, H, D, E, F, C, A
$ composer require nicmart/tree 

Источник

Оцените статью