68 lines
1.8 KiB
PHP
68 lines
1.8 KiB
PHP
|
<?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);
|