Skip to content

Instantly share code, notes, and snippets.

@boy3vil
Last active August 5, 2019 09:29
Show Gist options
  • Save boy3vil/5728e9476371afabd8a9408d7379e9c1 to your computer and use it in GitHub Desktop.
Save boy3vil/5728e9476371afabd8a9408d7379e9c1 to your computer and use it in GitHub Desktop.
PHP,, Create Tree Child Parent JSON from DB
$data = [
['id'=>1, 'id_parent'=>0],
['id'=>2, 'id_parent'=>1],
['id'=>3, 'id_parent'=>1],
['id'=>4, 'id_parent'=>2]
];
$tree = [];
$temp_tree = [];
foreach ($data as $key => $value) {
if(empty($value['id_parent'])){
$tree[$value['id']]=[];
}
else{
$tree[$value['id_parent']][$value['id']]=[];
$temp_tree[$value['id']]=&$tree[$value['id_parent']];
}
}
foreach ($tree as $key => $value) {
if(!empty($temp_tree[$key])){
$temp_tree[$key][$key]=&$tree[$key];
if(!empty($temp_tree[$key][$key]))
unset($tree[$key]);
}
}
die(json_encode($tree));
/*
output :
{
"1": {
"2": {
"4":[]
},
"3":[]
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment