Answer the question
In order to leave comments, you need to log in
How to find all subcategories of a selected category?
There is a table of the form:
How, knowing the id of the category, find out the id of all nested subcategories?
This is needed to display category articles.
For example, knowing id 3, how to find out id 6 and id 7, since in this case they are nested categories.
Or knowing id 6 how to find out id 7 and so on.
As far as I understand, a recursive function is needed here, but I myself have not mastered it.
Answer the question
In order to leave comments, you need to log in
I would recommend you a literature to broaden your horizons: https://www.arbinada.com/node/25
Pay special attention to the "Bypass Route".
As for your question, it depends on how you need to get the result - flat or voluminous.
For simplicity, suppose we want the result to be flat
<?php
/* @var array[] Плоский массив вложенных нод */
$arTree = [];
collectTree( 3, $arTree );
/*
Если сделать var_dump($arTree);
Мы рассчитываем получить следующий массив:
array
{
{
id: 3
title: Cat3
slug: cat3
parent: 0
},
{
id: 6
title: lodki
slug: lodki
parent: 3
},
{
id: 7
title: Samolety
slug: lodki
parent: 6
}
}
*/
function collectTree( $iRootId, $nodeList = [] )
{
/* @var array Массив описывающий ноду $iRootId */
$nodeList[ $iRoot ] = getRootData($iRootId);
/* @var int[] Массив id категорий, который является вложенным по отношению к текущей ноде */
$arRootIncludedNodeId = getSubTreeNodeIds( $iRootId );
if ( !empty( $arRootIncludedNodeId ) )
{
foreach ($arRootIncludedNodeId as $iNode)
{
collectTree( $iNode, $nodeList );
}
}
}
/**
* Возвращает данные по конкретной ноде
* @param int $iRoot
* @return array
*/
function getRootData( $iRoot )
{
// ...
}
/**
* Возвращает ID всех нод, являющихся наследниками $iRoot ноды
* @param int $iRoot
* @return int[]
*/
function getSubTreeNodeIds( $iRoot )
{
// ...
}
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question