<?php
$result= <<<XML
<?xml version='1.0' encoding='WINDOWS-1251'?>
<categories>
<category id="20001" >Сетевое оборудование</category>
<category id="20002" >Контроль доступа</category>
<category id="20003" >Видеонаблюдение</category>
<category id="20004" >Источники питания</category>
<category id="20011" parentId="20004" >Аккумуляторы</category>
<category id="20012" parentId="20003" >Аналоговые видеокамеры</category>
<category id="20013" parentId="20002" >Считыватели</category>
<category id="21247" parentId="20001" >GOAL city</category>
<category id="20326" parentId="20013" >Komkom</category>
<category id="20400" parentId="20012" >HikVision</category>
<category id="20618" parentId="20011" >ITV</category>
<category id="20619" parentId="20011" >ISS</category>
<category id="20620" parentId="20011" >DSSL</category>
</categories>
XML;
$text = iconv('UTF-8', 'CP1251', $result);
$tree = [];
/********************************************
* Функции для помощи в построениии крошек
*******************************************/
function haveChild($tree, $id) {
foreach ($tree as $item) {
if (isset($item['parentId']) && $item['parentId'] == $id) { return true;
}
}
return false;
}
function buildBreadcrumbs($tree, $elem, $level) {
$breadcrumbs = $elem['text'];
if (isset($elem['parentId'])) { $item = [];
for ($i = 0; $i < count($tree); ++$i) { if ($elem['parentId'] == $tree[$i]['id']) {
$item = $tree[$i];
break;
}
}
$tmp = $breadcrumbs;
$arrow = ($level == 0 ? '' : ' > ' );
$level = $level + 1;
$breadcrumbs = buildBreadcrumbs($tree, $item, $level).$tmp.$arrow;
$level = $level - 1;
}
return $breadcrumbs;
}
/**********************************************/
// формируем массив из xml структуры
for ($i = 0; $i < $count; ++$i) {
$arr = [];
$attr = $xml->category[$i]->attributes();
$arr['id'] = (int)$attr->id;
$arr['parentId'] = (int)$attr->parentId;
$arr['text'] = (string)$xml->category[$i];
$tree[$i] = $arr;
}
$breadcrumbsArray = [];
foreach ($tree as $item) {
// Если у узла нет потомка, значит это крайний узел.
// Будем строить путь до него
if (!haveChild($tree, $item['id'])) {
$breadcrumbsArray[$item['id']] = buildBreadcrumbs($tree, $item, 0);
}
}
echo '<pre>';
//print_r($tree);
echo '</pre>';