Php calls recursive functions multiple times. recursive functions are as follows:
/*** Recursively retrieve the subclass of a specified category * @ params $ categories array of all categories * @ params $ parent_id int parent class id: top-level category by default * @ return $ arr array subclass array obtained **/function get_child_category ($ categories, $ parent_id = 0) {static $ arr = array (); foreach ($ categories as $ category) {if ($ category ['parent _ id'] = $ parent_id) {$ arr [] = $ category; get_child_category ($ categories, $ category ['cat _ id']) ;}} return $ arr ;}
Problem Description: I want to use this function to obtain the subclass of the specified parent class. there is no problem with the first call. from the second call, this function is called each time, the results obtained last time are saved in the obtained array. for example, there are top-level classes A, B, and C. There are three sub-classes a1, a2, and a3 under Class, B has three sub-classes: b1, b2, and b3. When this function is called for the first time, all the sub-classes under A are obtained. when the function is called for the second time, the sub-classes b1, b2, and b3 under B are obtained. However, a1, a2, and a3 are obtained, b1, b2, b3, I think it should be a static variable problem, but if static variables are not used, they cannot be saved in Recursion. after static variables are used, the above situation occurs again, I want to clear the data obtained last time after calling a recursive function. I don't know how to solve this problem. thank you for your understanding!
Reply to discussion (solution)
Passed as parameter
function get_child_category($categories,$parent_id=0, $arr=array()){ foreach ($categories as $category){ if ($category['parent_id']==$parent_id){ $arr[]=$category; $arr = get_child_category($categories,$category['cat_id'], $arr); } } return $arr;}To reduce memory overhead, you can pass references
function get_child_category(&$categories, $parent_id=0, &$arr=array()){ foreach ($categories as $category){ if ($category['parent_id']==$parent_id){ $arr[]=$category; get_child_category($categories, $category['cat_id'], $arr); } } return $arr;}Call
print_r(get_child_category($ar, 0));print_r(get_child_category($ar, 2));
The problem has been solved. thank you very much for your enthusiastic help !!!