Unlimited classification, querying data from the database, and recursively performing custom sorting in the array. I also realized that there are many shortcomings and they are not handled well. There may be a better way. Let's discuss it together. It's more than 100 lines. Not all
- class Tree{
- protected $arr = array(); //Sort array
- protected $info = array(); //Storage error information
- protected $tree = array(); //Storage generated class array
- protected $flag = true; //Flag bit
-
- public function __construct()
- {
-
- }
- //Get data
- public function data($fid,$arr)
- {
- $this->checkArr($arr );
- $this->checking();
- $this->chindAll($fid);
- return $this->tree;
- }
-
- //Judge whether the parameters meet the requirements
- protected function checkArr($ val)
- {
- static $num = 0;
- if(is_array($val)){
- foreach($val as $Varr){
- $this->isKeyVal('id', $Varr, $num);
- $this->isKeyVal('parentid', $Varr, $num);
- $this->isKeyVal('name', $Varr, $num);
- $num++;
- }
- }
- $this- >arr = $val;
- }
- //Whether the stored id is an array
- protected function checkNum($val)
- {
- if(!is_numeric($val)){
- $this->info[] = ' The incoming parameter '.$val.' is not a numerical value';
- $this->flag = false;
- $this->checking();
- }
- }
- //Verification, output error message
- protected function checking( ){
- if(!$this->flag){
- echo '
';
- var_dump($this->info);
- exit();
- }
- }
-
- //Judge array key Whether it exists and whether it has a value
- protected function isKeyVal($key, $arr, $num)
- {
- if(!array_key_exists($key, $arr))
- {
- $this->info[] = $num. 'Array key'.$key.'does not exist';
- $this->flag = false;
-
- }
- }
-
- //Get the son
- public function getChind($fid)
- {
- static $num = 0 ;
- $arr = array();
- $this->checkNum($fid);
- foreach($this->arr as $key=>$row){
- if( $row['parentid'] == $fid){
- $arr[] = $row;
- unset($this->arr[$key]);
- }
- }
- if(!empty($arr)){
- $num++;
- return $this->sortArr($arr);
- }else{
- return null;
- }
- }
-
- //Get my son and grandson
- public function chindAll($fid,$input=null)
- {
- static $ n =0;
- $n++;
- $arr = $this->getChind($fid);
- if(!empty($arr)){
- $count = count($arr);
- if(empty($ input)){
- for($i=0; $i<$count ;$i++){
- $this->tree[$i] = $arr[$i];
- }
Copy code
|