1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace StefanoTree\NestedSet; |
||
6 | |||
7 | class Utilities |
||
8 | { |
||
9 | /** |
||
10 | * Convert flat tree structure to nested. |
||
11 | * |
||
12 | * @param array $flatTree |
||
13 | * @param string $levelName |
||
14 | * |
||
15 | * @return array |
||
16 | */ |
||
17 | 6 | public static function flatToNested( |
|
18 | array $flatTree, |
||
19 | string $levelName = 'level' |
||
20 | ): array { |
||
21 | 6 | return self::_flatToNested($flatTree, $levelName); |
|
22 | } |
||
23 | |||
24 | /** |
||
25 | * @param array $flatTree |
||
26 | * @param string $levelName |
||
27 | * @param null|int $level |
||
28 | * @param int $startPos |
||
29 | * @param array $result |
||
30 | * |
||
31 | * @return array |
||
32 | */ |
||
33 | 6 | private static function _flatToNested( |
|
34 | array $flatTree, |
||
35 | string $levelName = 'level', |
||
36 | ?int $level = null, |
||
37 | int $startPos = 0, |
||
38 | array &$result = array() |
||
39 | ): array { |
||
40 | 6 | $total = count($flatTree); |
|
41 | 6 | $first = true; |
|
42 | |||
43 | 6 | for ($pos = $startPos; $pos < $total; ++$pos) { |
|
44 | 6 | $item = $flatTree[$pos]; |
|
45 | |||
46 | 6 | if (null === $level) { |
|
47 | 6 | $level = $item[$levelName]; |
|
48 | } |
||
49 | |||
50 | 6 | if (!array_key_exists('_children', $item)) { |
|
51 | 6 | $item['_children'] = array(); |
|
52 | } |
||
53 | |||
54 | 6 | if ($level == $item[$levelName]) { |
|
55 | 6 | $result[] = $item; |
|
56 | 6 | $first = true; |
|
57 | 6 | } elseif (($level + 1) == $item[$levelName] && true == $first) { |
|
0 ignored issues
–
show
|
|||
58 | 6 | $children = array($item); |
|
59 | 6 | self::_flatToNested($flatTree, $levelName, (int) $item[$levelName], $pos + 1, $children); |
|
60 | 6 | $result[count($result) - 1]['_children'] = $children; |
|
61 | 6 | $first = false; |
|
62 | 6 | } elseif ($level > $item[$levelName]) { |
|
63 | 2 | break; |
|
64 | } |
||
65 | } |
||
66 | |||
67 | 6 | return $result; |
|
68 | } |
||
69 | } |
||
70 |
When comparing two booleans, it is generally considered safer to use the strict comparison operator.