Created
August 11, 2020 07:13
-
-
Save djamol/ceade804dc126f7b769f21d17784f7c4 to your computer and use it in GitHub Desktop.
This file contains 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 | |
$json ='[ | |
{ | |
"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" | |
} | |
]'; | |
$json = json_decode($json,true); | |
$outPut = generateArrayTree($json); | |
echo json_encode($outPut); | |
function generateArrayTree($datas, $parent = 0, $depth=0){ | |
$length=count($datas); $branch = array(); | |
if($length === 0 || $depth > 1000) return ''; | |
for($i=0; $i < $length; $i++){ | |
if($datas[$i]['parent'] == $parent){$node=array(); | |
$children =generateArrayTree($datas, $datas[$i]['id'], $depth+1); | |
$node['id'] = $datas[$i]['id']; | |
$node['parent'] = $datas[$i]['parent']; | |
$node['name'] = $datas[$i]['name']; | |
if($children){ | |
$node['children']=$children; | |
} | |
$branch[]= $node; | |
// $branch[] = array('id' => $datas[$i]['id'], 'parent' => $datas[$i]['parent'],'name' => $datas[$i]['name'], 'children' => generateArrayTree($datas, $datas[$i]['id'], $depth+1) ); | |
} | |
} | |
return $branch; | |
} | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment