PHP code example of yunaweb / bitrix-section-tree

1. Go to this page and download the library: Download yunaweb/bitrix-section-tree library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yunaweb / bitrix-section-tree example snippets


use Yunaweb\SectionTree\SectionTree;

$sections = [
    ['ID' => 1, 'IBLOCK_SECTION_ID' => null, 'NAME' => 'Каталог'],
    ['ID' => 2, 'IBLOCK_SECTION_ID' => 1, 'NAME' => 'Телефоны'],
    ['ID' => 3, 'IBLOCK_SECTION_ID' => 1, 'NAME' => 'Ноутбуки'],
];

$tree = SectionTree::toTree($sections);
// $tree[0]['NAME'] === 'Каталог'
// $tree[0]['CHILDREN'][0]['NAME'] === 'Телефоны'

$flat = SectionTree::toFlat($tree);
// $flat[1]['DEPTH'] === 1
// $flat[1]['PATH'] === [1, 2]

$chain = SectionTree::breadcrumbs($sections, 2);
// array_column($chain, 'NAME') === ['Каталог', 'Телефоны']

use Bitrix\Iblock\SectionTable;
use Yunaweb\SectionTree\SectionTree;

$rows = SectionTable::getList([
    'filter' => ['IBLOCK_ID' => 8],
    'select' => ['ID', 'IBLOCK_SECTION_ID', 'NAME', 'SORT'],
])->fetchAll();

$tree = SectionTree::toTree($rows);

$flat = SectionTree::toFlat(SectionTree::toTree($sections));

foreach ($flat as $section) {
    $indent = str_repeat('— ', $section['DEPTH']);
    echo '<option value="' . htmlspecialchars((string) $section['ID']) . '">'
        . $indent . htmlspecialchars($section['NAME']) . "</option>\n";
}

function renderMenu(array $items): string
{
    $html = '<ul>';
    foreach ($items as $item) {
        $html .= '<li>' . htmlspecialchars($item['NAME']);
        if ($item['CHILDREN'] !== []) {
            $html .= renderMenu($item['CHILDREN']);
        }
        $html .= '</li>';
    }

    return $html . '</ul>';
}

echo renderMenu(SectionTree::toTree($sections));

SectionTree::toTree($items, idKey: 'id', parentKey: 'parent_id');