Skip to content

Commit 5c4964a

Browse files
authored
Create Tree.php
1 parent 308010e commit 5c4964a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/Utils/Tree.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
namespace App\Utilities;
4+
5+
class CollectionUtility
6+
{
7+
/**
8+
* @param array $data
9+
* @param string $primary
10+
* @param string $parent
11+
* @param string $children
12+
* @return array
13+
* #
14+
*/
15+
public static function toTree($data, $primary = 'id', $parent = 'parent_id', $children = 'children')
16+
{
17+
if (!isset($data[0][$parent])) {
18+
return [];
19+
}
20+
21+
$items = array();
22+
foreach ($data as $v) {
23+
$items[$v[$primary]] = $v;
24+
}
25+
26+
$tree = array();
27+
foreach ($items as $item) {
28+
if (isset($items[$item[$parent]])) {
29+
$items[$item[$parent]][$children][] = &$items[$item[$primary]];
30+
} else {
31+
$tree[] = &$items[$item[$primary]];
32+
}
33+
}
34+
35+
return $tree;
36+
}
37+
}

0 commit comments

Comments
 (0)