A
A
Alexander Pankov2019-09-26 11:23:21
PHP
Alexander Pankov, 2019-09-26 11:23:21

How to implement a recursive traversal of store categories?

Hello, the task is to parse data from a remote site.
There is a page with categories of the 1st level, when you click on a category, you get to a page with categories of the 2nd level and so on.
in theory, the nesting is something like this

Балкон и сад
  Грили
  Зонты
    Балконные экраны
    Зонты от солнца и основания для зонтов
    Шатры и тенты
      Шатры
      Тенты
  Кашпо и растения для сада
    Растения
    Шпаллеры
Ванная
...

i want to write a function which would return me an array according to these categories
$result = [
    [
        'name' => 'Грили',
        'link' => 'url/url/url/',
        'dirs' => [
            [
                'name' => 'Грили декоративные',
                'link' => 'url/url/url/',
                'dirs' => []
            ],
            [
                'name' => 'Грили латунные',
                'link' => 'url/url/url/',
                'dirs' => []
            ]
        ]
    ],
    [...]
];

for this, I want to write a recursive function that would bypass each found address and build an array according to the example above, but I can’t do it, could you help, it’s possible to throw links where the recursion algorithms are clearly explained, you can even not on php , and on some pseudo code
, here is my code, but it doesn't work.
$result = [];
$topCats = getItemsCategory($document, $result); // передаю страницу с категориями верхнего уровня

function getItemsCategory(phpQueryObject $document, &$result)
{

    $childrens = pq($document)->find('.range-catalog-list__link')->elements;
    if ($childrens) { // есть потомки
        foreach ($childrens as $item) {
            $name = trim(pq($item)->find('.range-catalog-list__title')->text());
            $link = trim(pq($item)->attr('href'));

            if ($doc = phpQuery::newDocumentHTML(getSslPage($link)))
                $arReturn[]['dirs'] = getItemsCategory($doc);

            return [
                'name' => $name,
                'link' => $link,
            ];
        }
    } else { // нет потомков
        return [];
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hack504, 2019-09-26
@PankovAlxndr

Something like this you can try

$doc = new DOMDocument();
$doc->loadHTML($html);
$output = array();
showDOMNode($doc, $output );


function showDOMNode(DOMNode $domNode, $output) {
$i = 1;
    foreach ($domNode->childNodes as $node)
    {
        $output[$i] = array('name'=>$node->nodeName, 'value'=> $node->nodeValue, 'dirs'=> array());
        if($node->hasChildNodes()) {
            showDOMNode($node, $output[$i]['dirs']);
        }
        $i++;
    }    
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question