Home >Backend Development >PHP Tutorial >Find the number of all employees under each department in the department list, and there is a problem of repeated arrays when calling recursively
Question:
The code is as follows:
<code> //查找所有下级部门的id public static function actionSon($company_id,$id) { global $temp; $modelClass = self::find() ->where(['parent_id'=>$id,'company_id'=>$company_id]) ->all(); if(!empty($modelClass)){ foreach ($modelClass as $k => $value) { $temp[] =$value->id; self::actionSon($company_id,$value->id);//调用函数,传入参数,继续查询下级 } } return $temp; } </code>
<code>fields里面调用 public function fields() { return [ 'id', 'company_id' 'user_count'=>function(){ // return $this->getUserCount(); $dep_ids=self::actionSon($this->company_id,$this->id); // $GLOBALS['temp']=[]; //unset($temp); print_r($dep_ids); }, ]; }</code>
Result output:
Duplicate data is obtained. If there are departments in the list, it will continue to repeat. How to solve this problem?
The result I need is to get the IDs of all sub-departments under the current department every time I call it, and display them in the form of a one-dimensional array.
Release $GLOBALS['temp']=[]; to find only one level.
Question:
The code is as follows:
<code> //查找所有下级部门的id public static function actionSon($company_id,$id) { global $temp; $modelClass = self::find() ->where(['parent_id'=>$id,'company_id'=>$company_id]) ->all(); if(!empty($modelClass)){ foreach ($modelClass as $k => $value) { $temp[] =$value->id; self::actionSon($company_id,$value->id);//调用函数,传入参数,继续查询下级 } } return $temp; } </code>
<code>fields里面调用 public function fields() { return [ 'id', 'company_id' 'user_count'=>function(){ // return $this->getUserCount(); $dep_ids=self::actionSon($this->company_id,$this->id); // $GLOBALS['temp']=[]; //unset($temp); print_r($dep_ids); }, ]; }</code>
Result output:
Duplicate data is obtained. If there are departments in the list, it will continue to repeat. How to solve this problem?
The result I need is to get the IDs of all sub-departments under the current department every time I call it, and display them in the form of a one-dimensional array.
Release $GLOBALS['temp']=[]; to find only one level.