Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question