X
X
xacseo2017-07-22 09:38:50
PHP
xacseo, 2017-07-22 09:38:50

How to find all subcategories of a selected category?

There is a table of the form:
1ec44e9be4094ea18b374905840b04e3.png
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

1 answer(s)
A
Andrey Nikolaev, 2017-07-22
@gromdron

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 )
{
  // ...
}
?>

Accordingly, for a volumetric one, you need to slightly change the collectTree method so that it does not supplement the list, but appends to the desired element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question