This commit is contained in:
Anthony Axenov 2022-01-11 08:20:17 +08:00
parent acc214dfaa
commit 9abc140010
Signed by: anthony
GPG Key ID: EA9EC32FF7CCD4EC

67
php/menu.php Normal file
View File

@ -0,0 +1,67 @@
<?php
// https://gist.github.com/anthonyaxenov/d3b8da3bf569aa0143eed5526b372d30
// Пример рекурсивного вывода меню
$nav = [
[
'name' => 'Home',
'title' => 'Homepage',
// ...something else...
'sub' => [
[
'name' => 'sub11',
'title' => null,
// ...something else...
'sub' => [
[
'name' => 'sub111',
'title' => 'This is the Sub 111',
],
],
],
[
'name' => '',
'title' => 'This is the Sub 12',
'sub' => [
[
'name' => null,
'title' => 'This is the Sub 121',
],
],
],
],
],
[
'name' => 'sub2',
'title' => 'This is the Sub 2',
'sub' => [
[
'name' => 'sub21',
'title' => 'This is the Sub 21',
],
],
],
];
function has_submenu($menu): bool
{
return is_array($menu)
&& isset($menu['sub'])
&& !empty($menu['sub'])
&& is_array($menu['sub']);
}
function print_menu(array $menu, int $level = 0)
{
$ident = '';
foreach ($menu as $element) {
$ident = str_pad($ident, $level);
echo $ident.'Name: '.($element['name'] ?? '(empty)').PHP_EOL;
echo $ident.'Title: '.($element['title'] ?? '(empty)').PHP_EOL;
echo $ident.'Url: '.($element['url'] ?? '(empty)').PHP_EOL;
echo $ident.'Submenu:'.(has_submenu($element) ? '' : ' (empty)' ).PHP_EOL;
if (has_submenu($element)) {
print_menu($element['sub'], $level += 4);
}
$level -= 4;
}
}
print_menu($nav);