<?php
$two_dimention = [
["id" => 4, "name" => "Home", "parent" => 0, "depth" => 0],
["id" => 5, "name" => "Menu 1", "parent" => 0, "depth" => 0],
["id" => 6, "name" => "Menu 2", "parent" => 0, "depth" => 0],
["id" => 8, "name" => "Menu 2.1", "parent" => 6, "depth" => 1],
["id" => 10, "name" => "Menu 2.1.1", "parent" => 8, "depth" => 2],
["id" => 11, "name" => "Menu 2.1.2", "parent" => 8, "depth" => 2],
["id" => 9, "name" => "Menu 2.2", "parent" => 6, "depth" => 1],
["id" => 7, "name" => "Menu 3", "parent" => 0, "depth" => 0],
["id" => 18, "name" => "Menu 3.1", "parent" => 7, "depth" => 1],
];
function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
$m = [];
foreach ($d as $e) {
isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];
isset($m[$e[$k]]) ?: $m[$e[$k]] = [];
$m[$e[$pk]][] = array_merge($e, [$c => &$m[$e[$k]]]);
}
return $m[$r]; // remove [0] if there could be more than one root nodes
}
function nested2ul($data)
{
$result = [];
if (sizeof($data) > 0) {
$result[] = '<ul>';
foreach ($data as $entry) {
$result[] = sprintf(
'<li>%s %s</li>',
$entry['name'],
nested2ul($entry['children'])
);
}
$result[] = '</ul>';
}
return implode($result);
}
$temp= makeRecursive($two_dimention);
echo nested2ul($temp);
preferences:
47.58 ms | 402 KiB | 5 Q