<?php
$arr = array(
[
"name" => "cat1",
"id" => "1",
"parent" => "",
],
[
"name" => "cat2",
"id" => "2",
"parent" => "",
],
[
"name" => "subcat1",
"id" => "6",
"parent" => "1",
],
[
"name" => "subsubcat1",
"id" => "7",
"parent" => "6",
],
[
"name" => "subcat2",
"id" => "5",
"parent" => "2",
],
);
function list_item($arr, $item) {
echo "<li>{$item['name']}</li>\n";
// find any children
$children = array_filter($arr, function ($i) use ($item) { return $i['parent'] == $item['id']; });
if (!empty($children)) {
echo "<ul>\n";
foreach ($children as $child) {
list_item($arr, $child);
}
echo "</ul>\n";
}
}
$parents = array_filter($arr, function ($item) { return !$item['parent'];});
echo "<ul>\n";
foreach ($parents as $parent) {
list_item($arr, $parent);
}
echo "</ul>\n";
preferences:
28.04 ms | 404 KiB | 5 Q