There is the following array [id] => [parent_id]

Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 1 [6] => 2 [7] => 1 [8] => 3 [9] => 5 [10] => 5 [11] => 0 [12] => 3 [13] => 4 [14] => 9 [15] => 9 [16] => 9 [17] => 4 [18] => 4 [19] => 2 [20] => 2 [21] => 1 [22] => 1 [23] => 5 [24] => 5 [25] => 14 [26] => 14 [27] => 19 [28] => 19 [29] => 27 [30] => 28 ) 

Help with writing a function that, according to a given id key, will enter the id keys of the children into a new array. Those. if, for example, to set the initial key 5, then the array with the following numbers should return: 5,9,10,23,24,14,15,16,25,26 The order of numbers is not important

  • To be honest, I didn’t understand by your example. "5,9,10,23,24,14,15,16,25,26" - Node_pro
  • we take the initial key 5. We are looking for an element with id = 5. We enter into an array. Further we search for all elements with parent_id = 5. We transfer them to an array. Then we take the id of these elements and look for elements with such parent_id, etc. - Demyan112rv

1 answer 1

Shovel the list by building a full tree (if it is a tree, of course). Take the next peak from the list, stick it in place, repeat.

When will you have (I write with the notation […]Array(…) )

 [1 => [5 => [9 => [14 => …, 15 => [], 16 => []], 10 => …, 23 => …, 24 => …], 7 => …, 21 => …, 22 => …], 2 => …, 3 => …, 4 => …] 

That working with wood will be trivial. The resulting tree, of course, is to save and use instead of a list wherever required.

If you do not want to build a tree, or cycles are possible in the graph, then just look for the next descendants and add. Pseudocode:

 function children(graph, node) { // graph — ваш массив, node — начальный ключ result = {node}; // Множество-результат pending = {node}; // Множество узлов, ожидающих обработки while (count(pending) > 0) { // Пока есть непросмотренные узны node = pending.pop(); // Вытаскиваем из мн-ва любой узел if (!result.contains(node)) { // Защита от циклов, если уже видели такой children = array_keys(graph, node, true); // Находим непосредств. детей pending += children; // Запоминаем для обработки result += children; // И добавляем к результату } } return result; } 

I hope the idea is clear, and it will be easy to do next.

I used the pseudo-syntax {} to denote the set. In PHP, there is no “set” type, but it can be emulated by an associative array in which key values ​​are ignored.