php - Transform simple array in hierarchy array -
i'm looping trough below array has multiple entries. in example have 3 elements each element have 3 values inside.
[0] ['name'] => 'aaa' ['id'] => 38679 ['parent-id'] => 0 [1] ['name'] => 'bbb' ['id'] => 38830 ['parent-id'] => 38679 [2] ['name'] => 'ccc' ['id'] => 38680 ['parent-id'] => 38830
so, looping trough array, need construct 1 in format (the idea construct hierarchy):
[0] [38679] => 'aaa' [38830] => 'bbb' [38680] => 'ccc'
maybe there's way this. suggestion great.
one of possible solutions use recursive function:
$test = [ 0 => [ 'name' => 'aaa', 'id' => 38679, 'parent-id' => 0 ], 1 => [ 'name' => 'bbb', 'id' => 38830, 'parent-id' => 38679 ], 2 => [ 'name' => 'ccc', 'id' => 38680, 'parent-id' => 38830 ] ]; function make_hierarchy(array $arr, $parent = 0) { $result = array(); foreach($arr $item) { if ($item['parent-id'] == $parent) { $children = make_hierarchy($arr, $item['id']); $child = $item; if ($children) { $child['children'] = $children; } $result[] = $child; } } return $result; } $r = make_hierarchy($test); var_dump($r);
Comments
Post a Comment