PHP
4
Вклад в тег
function tree ($data = [], $parent = 'parent', $child = 'child') {
if (!empty($data)) {
$tree = [];
foreach($data as $id => &$row) {
if (empty($row[$parent])) {
$tree[$id] = &$row;
} else {
$data[$row[$parent]][$child][$id] = &$row;
}
}
return $tree;
}
}
$data = [
1 => [
'name' => 1,
'parent' => 0
],
2 => [
'name' => 2,
'parent' => 1
],
3 => [
'name' => 3,
'parent' => 1
],
4 => [
'name' => 4,
'parent' => 3
],
5 => [
'name' => 5,
'parent' => 4
]
];
print_r(tree($data));
function recursion (array $data = []) {
foreach ($data as $row) {
if (isset($row['id'])) {
echo '<div>' . $row['name'] . '</div>';
echo '<div class="child">';
if (isset($row['child'])) {
recursion($row['child']);
}
echo '</div><br>';
}
}
}
recursion(tree($data));
<div>один</div>
<div class="child">
<div>два</div>
<div class="child"></div>
</div>
<div>три</div>
<div class="child">
<div>четыре</div>
<div class="child">
<div>пять</div>
<div class="child"></div>
</div>