E
E
Evgeniy V.2019-02-22 16:42:15
PHP
Evgeniy V., 2019-02-22 16:42:15

How to organize a recursive enumeration?

function get_cat_recursive($id_check, $array_check, $array_temp)
{

  foreach ($array_check as $key => $value) {
    
    if ( $id_check == $value['parent_id']) {

      array_push($array_temp, $value['id']);
      get_cat_recursive($value['id'], $array_check, $array_temp);

    }

  }
  return $array_temp;

}

There is an array
5c6ffb4be133d008361751.jpeg
This array is used to display me and categories. Products belong only to categories of the last level of nesting, assuming there is a full path to the subcategory: Fishing -> Rod -> Bologna rod, the id of the category "Bologna rod" will be recorded for the product, but I need to display all products that are included in all subcategories of the category " Fishing". To do this, you need to get the id of all subcategories included in Fishing. I'm trying to write a recursive iteration, but for some reason it only works for one level of nesting. How to make it so that when passing the fishing category id to the function, the result would be an array with the id of all subcategories?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
artem78, 2019-02-22
@volkovecgenei

You have an error: when you make a recursive call, the values ​​found in it are NOT merged with the current ones. This is how it should be:
And it is better to pass an array for the result by reference and each function call will add to it what it found. The original array is also desirable by reference, so that each time the function is called, it is not copied in memory.

function get_cat_recursive($id_check, &$array_check, &$array_temp)
{

  foreach ($array_check as $key => $value) {
    
    if ( $id_check == $value['parent_id']) {

      array_push($array_temp, $value['id']);
      get_cat_recursive($value['id'], $array_check, $array_temp);

    }

  }

}

// Использование
$result = []; // При первом вызове функции передаём пустой массив
get_cat_recursive(2, $all_cats, $result);
print_r($result);

A
Adamos, 2019-02-22
@Adamos

You don't have a recursive function. You need to pass &$array_temp into it, since you are filling it.
And so each recursive call works with its copy - idly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question