Last active
February 25, 2022 07:24
-
-
Save nook-ru/2a480824b1dc2668016ea4a04831f812 to your computer and use it in GitHub Desktop.
bitrix:menu template helpers, иерархическое, многоуровневое меню
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die(); | |
/** | |
* Раскладывает одноуровневый массив пунктов bitrix:menu в иерархию: | |
* дочерние пункты меню попадают в массив CHILDREN родительского. | |
* | |
* @param array $arResult | |
* @return array | |
*/ | |
$makeNested = static function (array $arResult) { | |
$menuList = array(); | |
$parents = array(); | |
foreach ($arResult as $arItem) { | |
$lev = $arItem['DEPTH_LEVEL']; | |
if ($arItem['IS_PARENT']) { | |
$arItem['CHILDREN'] = []; | |
} | |
if ($lev == 1) { | |
$menuList[] = $arItem; | |
$lastInd = count($menuList)-1; | |
$parents[$lev] = &$menuList[$lastInd]; | |
} else { | |
$parents[$lev-1]['CHILDREN'][] = $arItem; | |
$lastInd = count($parents[$lev-1]['CHILDREN'])-1; | |
$parents[$lev] = &$parents[$lev-1]['CHILDREN'][$lastInd]; | |
} | |
} | |
return $menuList; | |
}; | |
/** | |
* Собирает результат работы $makeNested обратно в плоский список | |
* для передачи в привычный template.php компонента меню | |
* | |
* @param array $items | |
* @return array | |
*/ | |
$makeFlat = static function (array $items) use (&$makeFlat) { | |
$result = []; | |
foreach ($items as $idx => $item) { | |
$result[] = array_diff_key($item, ['CHILDREN' => 1]); | |
if (isset($item['CHILDREN'])) { | |
$result = array_merge($result, $makeFlat($item['CHILDREN'])); | |
} | |
} | |
return $result; | |
}; | |
$nestedResult = $makeNested($arResult); | |
// здесь удобно что-то поменять, например, отсортировать или отфильтровать родительские пункты меню | |
$arResult = $makeFlat($nestedResult); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment