-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTreeToList.php
64 lines (49 loc) · 1.52 KB
/
TreeToList.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);
namespace axios\tools;
use axios\tools\traits\CallPropTrait;
/**
* Class TreeToList.
*
* @method string parent_index($parent_index = null)
* @method string node_index($node_index = null)
* @method string node_name($node_name = null)
* @method string layer_name($layer_name = null)
*/
class TreeToList
{
use CallPropTrait;
private array $tree;
private string $parent_index = 'parent_id';
private string $node_index = 'id';
private string $node_name = 'child';
private string $layer_name = '';
private int $count;
public function __construct(array $tree = [])
{
$this->tree = $tree;
}
public function toList(): array
{
$this->count = 0;
$this->recurse($data, $this->tree);
return $data;
}
private function recurse(?array &$data = [], array $tree = [], int $layer = 0, int $parent_id = 0): void
{
foreach ($tree as $t) {
++$this->count;
$node = $t;
$node[$this->node_index] = $this->count;
$node[$this->parent_index] = $parent_id;
unset($node[$this->node_name]);
if ('' !== $this->layer_name) {
$node[$this->layer_name] = $layer;
}
$data[] = $node;
if (isset($t[$this->node_name]) && !empty($t[$this->node_name])) {
$this->recurse($data, $t[$this->node_name], $layer + 1, $this->count);
}
}
}
}