Skip to content

Instantly share code, notes, and snippets.

@azinkey
Created October 31, 2018 13:44
Show Gist options
  • Save azinkey/f3a719b40c0d7c0d653ee0e4d2d0671d to your computer and use it in GitHub Desktop.
Save azinkey/f3a719b40c0d7c0d653ee0e4d2d0671d to your computer and use it in GitHub Desktop.
Parent Child Flat array to Tree/List
<?php
$a = '[{"id":"21","name":"Clothes","parent":"52"},{"id":"28","name":"category-D","parent":"21"},{"id":"29","name":"Category-E","parent":"28"},{"id":"30","name":"Category-F","parent":"29"},{"id":"31","name":"category-G","parent":"30"},{"id":"48","name":"category-Y","parent":"0"},{"id":"51","name":"category name","parent":"48"},{"id":"52","name":"categoryAAA","parent":"0"},{"id":"53","name":"category","parent":"52"},{"id":"54","name":"Clothes","parent":"0"},{"id":"55","name":"Cloth","parent":"171"},{"id":"56","name":"Headphone","parent":"1455555"},{"id":"57","name":"Mobile","parent":"2147483647"},{"id":"59","name":"category","parent":"21"},{"id":"61","name":"Shirt","parent":"59"},{"id":"62","name":"Shoes","parent":"0"},{"id":"63","name":"Smartphones","parent":"0"},{"id":"64","name":"Test Category Test","parent":"0"},{"id":"65","name":"Smartphones","parent":"21"},{"id":"66","name":"Charger","parent":"21"},{"id":"71","name":"CheckTime","parent":"0"},{"id":"72","name":"category","parent":"0"},{"id":"73","name":"sample cat 1","parent":"0"},{"id":"74","name":"category#@$%#$","parent":"0"},{"id":"76","name":"Shorts","parent":"0"},{"id":"77","name":"Shorts","parent":"21"},{"id":"78","name":"Watch","parent":"0"},{"id":"80","name":"Men watch","parent":"78"},{"id":"82","name":"ABC TEST Product","parent":"0"},{"id":"83","name":"product Test Name","parent":"0"},{"id":"84","name":"avisual","parent":"0"},{"id":"85","name":"Test12","parent":"0"},{"id":"86","name":"test 12","parent":"0"},{"id":"87","name":"test14","parent":"0"},{"id":"88","name":"Mobile","parent":"63"},{"id":"89","name":"Accessories","parent":"88"},{"id":"90","name":"ttt","parent":"0"},{"id":"91","name":"New Test","parent":"0"},{"id":"111","name":"RELOAD","parent":"0"}]';
$data = json_decode($a, true);
$refs = array();
function buildTree($flat, $pidKey, $idKey = null) {
$grouped = array();
foreach ($flat as $sub) {
$grouped[$sub[$pidKey]][] = $sub;
}
$fnBuilder = function($siblings) use (&$fnBuilder, $grouped, $idKey) {
foreach ($siblings as $k => $sibling) {
$id = $sibling[$idKey];
if (isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
$tree = $fnBuilder($grouped[0]);
return $tree;
}
$tree = buildTree($data, 'parent', 'id');
echo '<ol>';
buildList($tree);
echo '</ol>';
function buildList($t, $name = null) {
foreach ($t as $r) {
$n = $name . $r['name'];
echo '<li>' . $n . '</li>';
if (isset($r['children'])) {
//$r['children']
buildList($r['children'],$n . ' &rArr; ');
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment