Created
October 21, 2021 09:23
-
-
Save Vijaysinh/575704d4de5dd3619acde109926e724b to your computer and use it in GitHub Desktop.
RecursiveParentChild.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = '[{"id":8,"parent":4,"name":"Food & Lifestyle"},{"id":2,"parent":1,"name":"Mobile Phones"},{"id":1,"parent":0,"name":"Electronics"},{"id":3,"parent":1,"name":"Laptops"},{"id":5,"parent":4,"name":"Fiction"},{"id":4,"parent":0,"name":"Books"},{"id":6,"parent":4,"name":"Non-fiction"},{"id":7,"parent":1,"name":"Storage"}]'; | |
$t = buildTree($arr); | |
print_r($t); | |
function buildTree(array $flatList) | |
{ | |
$grouped = []; | |
foreach ($flatList as $node){ | |
$grouped[$node['parent']][] = $node; | |
} | |
$fnBuilder = function($siblings) use (&$fnBuilder, $grouped) { | |
foreach ($siblings as $k => $sibling) { | |
$id = $sibling['id']; | |
if(isset($grouped[$id])) { | |
$sibling['children'] = $fnBuilder($grouped[$id]); | |
} | |
$siblings[$k] = $sibling; | |
} | |
return $siblings; | |
}; | |
return $fnBuilder($grouped[0]); | |
} | |
function build_tree(&$items, $parentId = null) { | |
$treeItems = []; | |
foreach ($items as $idx => $item) { | |
if((empty($parentId) && empty($item['parent'])) || (!empty($item['parent']) && !empty($parentId) && $item['parent'] == $parentId)) { | |
$items[$idx]['children'] = build_tree($items, $items[$idx]['id']); | |
$treeItems []= $items[$idx]; | |
} | |
} | |
return $treeItems; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment