I want to get automatically children element value from array. It's multidimentional array format. You can see array format as like below
Note : Child element automatically generate. So, not want to static code logic.
I want to create category tree and that array structure looks like this below array format :
Array
(
[0] => Array
(
[id] => 1
[parent_cat_name] => 0
[cat_name] => Test 1
[status] => 1
[position] => 1
[created_at] => 2019-09-03 09:27:45
[updated_at] => 2019-09-03 11:00:54
[children] => Array
(
[0] => Array
(
[id] => 2
[parent_cat_name] => 1
[cat_name] => Test 2
[status] => 1
[position] => 2
[created_at] => 2019-09-03 09:28:19
[updated_at] => 2019-09-03 11:01:00
[children] => Array
(
[0] => Array
(
[id] => 4
[parent_cat_name] => 2
[cat_name] => Test 4
[status] => 1
[position] => 4
[created_at] => 2019-09-03 09:35:20
[updated_at] => 2019-09-03 11:01:03
[children] => Array
(
[0] => Array
(
[id] => 5
[parent_cat_name] => 4
[cat_name] => Test 5
[status] => 1
[position] => 3
[created_at] => 2019-09-07 05:55:09
[updated_at] => 2019-09-07 05:55:09
)
)
)
)
)
)
)
[1] => Array
(
[id] => 3
[parent_cat_name] => 0
[cat_name] => Test 3
[status] => 1
[position] => 4
[created_at] => 2019-09-03 09:35:10
[updated_at] => 2019-09-03 11:00:58
)
)
Used code :
public function buildTree(array $elements, $parentId = 0) {
$branch = [];
foreach ($elements as $element) {
if ($element['parent_cat_name'] == $parentId) {
$children = $this->buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
Actual Result :
- Test 1
- Test 2
- Test 4
- Test 5
- Test 4
- Test 2
- Test 3