Infinite Pole Classification (Recursive)

Posted by igul222 on Tue, 07 May 2019 03:05:03 +0200

Infinite polar classification simply means that a class can be divided into several subclasses, and then one subclass can be divided into other subclasses indefinitely, as if windows could create a new folder, then create some folders in this folder, and some folders under the folder.

So how does PHP achieve its infinite classification?How do I list all its categories?

First, let's assume there is an array like this

$arr = array (0=>array ('cid'=>1,'pid'=>0,'name'=>'Asia'),
1=>array ('cid'=>2,'pid'=>0,'name'=>'North America'),
), 2=>array ('cid'=>3,'pid'=>1,'name'=>'China',
), 3=>array ('cid'=>4,'pid'=>2,'name'=>'United States',
), 4=>array ('cid'=>5,'pid'=>3,'name'=>'Beijing',
), 5=>array ('cid'=>6,'pid'=>3,'name'=>'hebei'),
), 6=>array ('cid'=>7,'pid'=>5,'name'=>'Dongcheng District'),
), 7=>array ('cid'=>8,'pid'=>5,'name'=>'seafloor',
),
);

We need a display like this here.
Write a picture description here

If we want to visualize this array as shown above, we need to use php recursion, so how?See the core code below

Copy Code

private function GetTree(arr,arr,arr,pid,$step){

global $tree;    foreach($arr as $key=>$val) {    
    if($val['pid'] == $pid) {        
        $flg = str_repeat('└―',$step);       
             $val['name'] = $flg.$val['name'];      
                   $tree[] = $val;          
                    $this->GetTree($arr , $val['cid'] ,$step+1);

    }

}    return $tree;

}

Copy Code
Then we just need to write one code call

$newarr = this−>GetTree(this->GetTree(this−>GetTree(arr, 0, 0);
Find all parent taxonomy information based on subclass id (in yii2 framework)

Method 1:

public static function get_parent_list(arr,arr,arr,id){

    //$arr All Categories List

    //$id parent taxonomy ID

    static $list=array();      
      foreach($arr as $u){    
              if($u['id']== $id){//The parent taxonomy id is equal to the id found
            $list[]=$u;      
                      if($u['parent_id']>0){   
                        self::get_parent_list($arr,$u['parent_id']);
            }

        }

    }       return $list;

}

This allows classification information to be stored in the cache without recursive queries.
Method 2: Recursive query for classification information

public static function get_parents($id){

static $list = [];     
   $cat_data = Category::findOne($id)->toarray(); 
          if($cat_data){        
              $list[] = $cat_data;    
              $id = $cat_data['parent_id'];    
               if($cat_data['parent_id'] > 0){ 
                     self::get_parents($id);

            }

}        return $list;

}

Since you need to implement an infinite classification, we need to know what its subcolumns are?

The last implemented array is in this form:

[php] view plain copyArray (

[0] => Array  
    (  
        [category_id] => 1  
        [category_name] => About me  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
    )  



[1] => Array  

    (  
        [category_id] => 2  
        [category_name] => Life Essays  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
    )  


[2] => Array  
    (  
       [category_id] => 3  
        [category_name] => Article Categories  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
        [category_child] => Array  
            (  

                [0] => Array  
                    (  
                        [category_id] => 4  
                        [category_name] => Linux The server  
                        [category_pid] => 3  
                        [category_addtime] => -28800  
                        [category_order] => 1  
                        [category_child] => Array  
                            (  
                                [0] => Array  
                                    (  
                                        [category_id] => 5  
                                        [category_name] => linux optimization  
                                        [category_pid] => 4  
                                        [category_addtime] => 0  
                                       [category_order] => 0  
                                    )  


                                [1] => Array  

                                    (  
                                        [category_id] => 6  
                                        [category_name] => Virtualization  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478228220  
                                        [category_order] => 0  
                                    )  

                                [2] => Array  
                                    (  
                                        [category_id] => 7  
                                        [category_name] => Mysql Optimization and Development  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478188800  
                                        [category_order] => 0  
                                    )  
                                [3] => Array  
                                    (  
                                        [category_id] => 8  
                                        [category_name] => High Availability and Virtualization  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478394120  
                                        [category_order] => 0  
                                    )  
                            )  
                    )  


                [1] => Array  
                    (  
                        [category_id] => 15  
                        [category_name] => Mysql  
                        [category_pid] => 3  
                        [category_addtime] => 1480555980  
                        [category_order] => 0  
                        [category_child] => Array  
                            (  
                                [0] => Array  
                                    (  
                                        [category_id] => 16  
                                        [category_name] => optimization  
                                        [category_pid] => 15  
                                        [category_addtime] => 1480555980  
                                        [category_order] => 0  
                                    )  
                                [1] => Array  
                                    (  
                                        [category_id] => 17  
                                        [category_name] => Sql programming  
                                        [category_pid] => 15  
                                        [category_addtime] => 1480556040  
                                        [category_order] => 8  
                                    )  
                            )  
                    )  
            )  
    )  

)

So how can we turn a two-dimensional array we take out of the database into one like this?
Give an example:

We want to implement the two-dimensional array below in the form above.

[php] view plain copy

$arr=array(

array('id'=>'1','name'=>'Beijing','pid'=>'0'),    

array('id'=>'2','name'=>'Shanghai','pid'=>'0'),    

array('id'=>'3','name'=>'Pudong','pid'=>'2'),    

array('id'=>'4','name'=>'Chaoyang','pid'=>'1'),    

array('id'=>'5','name'=>'Guangzhou','pid'=>'0'),    

array('id'=>'6','name'=>'Village','pid'=>'4'),   

array('id'=>'7','name'=>'Guangdong','pid'=>'5'),   

array('id'=>'8','name'=>'Sanli','pid'=>'4'),  

array('id'=>'10','name'=>'alley','pid'=>'8')  

);

First, use the same index of the array as the id number of the primary key to find subcolumns. First, add an index to the array:

[php] view plain copy

$arr=array(

1=>array('id'=>'1','name'=>'Beijing','pid'=>'0'),    

2=>array('id'=>'2','name'=>'Shanghai','pid'=>'0'),    

3=>array('id'=>'3','name'=>'Pudong','pid'=>'2'),    

4=>array('id'=>'4','name'=>'Chaoyang','pid'=>'1'),    

5=>array('id'=>'5','name'=>'Guangzhou','pid'=>'0'),    

6=>array('id'=>'6','name'=>'Village','pid'=>'4'),   

7=>array('id'=>'7','name'=>'Guangdong','pid'=>'5'),   

8=>array('id'=>'8','name'=>'Sanli','pid'=>'4'),  

10=>array('id'=>'10','name'=>'alley','pid'=>'8')  

);

Use indexed subscripts to determine if the column has a parent column, and if so, place the column in the son-child array of the parent column
[php] view plain copy

function generateTree($items){

$tree = array();  

foreach($items as $item){  

    //Determine if there is an index of the array==  

    if(isset($items[$item['pid']])){     //Find if there is this category in the array, such as isset ($items[0]) isset ($items[1])  

        $items[$item['pid']]['son'][] = &$items[$item['id']]; //As the content above changes, the value inside $tree changes  

    }else{  

        $tree[] = &$items[$item['id']];   //Give his address to $tree  

    }    

}  

return $tree;  

}

The main problem with this program above is that we added the index of the array manually?Can we automatically add an array index?Of course, the following program is implemented, automatically adding an index to the array and then putting the subcolumns into the son array of the parent column, thinking the same as the above program

[php] view plain copy

function make_tree(list,list,list,pk='id',pid=′pid′,pid='pid',pid=′pid′,child='_child',$root=0){

$tree=array();   

$packData=array();  

foreach ($list as  $data) {  



<span style="white-space:pre">    </span>//Convert to Array with Primary Key id  

    $packData[$data[$pk]] = $data; //$packData[1]=$data; $packData[2]=$data   

}  

foreach ($packData as $key =>$val){       

    if($val[$pid]==$root){   //Represents the following node         

        $tree[]=& $packData[$key];  

    }else{  

        //Find its parent  

        $packData[$val[$pid]][$child][]=& $packData[$key];  

    }  

}  

return $tree;  

}

Second method: use recursion to find subcolumns
Idea: Use recursion to find subcolumns in each column, and print until you find the last subcolumn and run debugging one more level out

Tree, for ease of understanding, you can print $tree to watch the array change

[php] view plain copy

array('id'=>'6','name'=>'Sanlitun','pid'=>'4'),

[php] view plain copy
function make_tree1(list,list,list,pk='id',pid=′pid′,pid=&#x27;pid&#x27;,pid=′pid′,child='_child',$root=0){
tree=array();foreach(tree=array(); foreach(tree=array();foreach(list as $key=> KaTeX parse error: Expected '}', got 'EOF' at end of input: …{ if(val[pid]==pid]==pid]==root){
//Get all the current pid subclasses unset (all pid subclasses) Unset (all subclasses of PID unset(list[key]);if(!empty(key]); if(! empty(key]);if(!empty(list)){
Child=make tree1 (child=make_tree1 (child=maket ree1 (list, pk, pk, pk, pid, child, child, val[pk]); //come to find subcolumn recursive empty if(!empty(pk]) in Beijing; //come to find subcolumn recursive empty in Beijing if(!empty(pk);//come to find subcolumn recursive empty if(!Empty(child){in Beijing
val[c′hild′]=val[&#x27;_child&#x27;]=val[c′​hild′]=child;
}
}
tree[]=tree[]=tree[]=val;
}
}
return $tree;
}

To better understand recursion, you can find a small program to test, for example, this summation program
You can analyze the output of $n from 2,3...10, instead of 10, 9 - 2, I understand how recursion in that program above works. In a word, recursion is interesting and I hope you can understand it well.
[php] view plain copy

function sum($n){
a=0;if(a=0; if(a=0;if(n>1){
a=sum(a=sum(a=sum(n-1)+n;/∗if(n; /*if(n;/∗if(n>5){
echo "KaTeX parse error: Expected 'EOF', got '}' at position 22: …/>" ; }̲*/ ech…n
";
}else{
$a=1;
}

return $a;  

}

echo sum(10);

Get data for all subclass id based on parent id

#$id = parent id, array = all classifications publicfunctiongetSon(array = all classifications public function getSon(array=all classifications public function getSon(id, $array){
static list;foreach(list; foreach (list;foreach(array as $k => KaTeX parse error: Expected '}', got 'EOF' at end of input: … if(v['parent_id'] == $id){
$list[] = array[array[array[k];
self::getSon(v[′id′],v[&#x27;id&#x27;],v[′id′],array);

        }

    }        return $list;

}

php infinite pole classification
First of all, what is the infinite pole classification?

Infinite Pole Classification Simple point is that a class can be divided into several subclasses, and then one subclass can be divided into other subclasses indefinitely, as if windows could create a new folder, then some folders can be built in this folder, and some folders can be built under the folder

So how does PHP achieve its infinite classification?How do I list all its categories?

First, let's assume there is an array like this

$arr = array (0=>array ('cid'=>1,'pid'=>0,'name'=>'Asia'),

),    1=>array(        'cid'=>2,        'pid'=>0,        'name'=>'North America',

),    2=>array(        'cid'=>3,        'pid'=>1,        'name'=>'China',

),    3=>array(        'cid'=>4,        'pid'=>2,        'name'=>'U.S.A',

),    4=>array(        'cid'=>5,        'pid'=>3,        'name'=>'Beijing',

),    5=>array(        'cid'=>6,        'pid'=>3,        'name'=>'HEBEI',

),    6=>array(        'cid'=>7,        'pid'=>5,        'name'=>'Dongcheng District',

),    7=>array(        'cid'=>8,        'pid'=>5,        'name'=>'Haidian District',

),

);

We need a display like this here.
Write a picture description here

If we want to visualize this array as shown above, we need to use php recursion, so how?See the core code below

Copy Code

private function GetTree(arr,arr,arr,pid,$step){

global $tree;  
  foreach($arr as $key=>$val) {   
     if($val['pid'] == $pid) {        
         $flg = str_repeat('└―',$step);        
             $val['name'] = $flg.$val['name'];          
               $tree[] = $val;         
                 $this->GetTree($arr , $val['cid'] ,$step+1);
    }

}    
return $tree;

}

Copy Code
Then we just need to write one code call

$newarr = this−&gt;GetTree(this-&gt;GetTree(this−>GetTree(arr, 0, 0);
Find all parent taxonomy information based on subclass id (in yii2 framework)

Method 1:

public static function get_parent_list(arr,arr,arr,id){

    //$arr All Categories List

    //$id parent taxonomy ID

    static $list=array();
            foreach($arr as $u){         
       if($u['id']== $id){//The parent taxonomy id is equal to the id found
            $list[]=$u;      
                      if($u['parent_id']>0){        
                        self::get_parent_list($arr,$u['parent_id']);
            }

        }

    }       return $list;

}

This allows classification information to be stored in the cache without recursive queries.
Method 2: Recursive query for classification information

public static function get_parents($id){
    static $list = [];        $cat_data = Category::findOne($id)->toarray();        if($cat_data){            $list[] = $cat_data;                    $id = $cat_data['parent_id'];                    if($cat_data['parent_id'] > 0){                            self::get_parents($id);
                }
    }        return $list;
}

Since you need to implement an infinite classification, we need to know what its subcolumns are?

The last implemented array is in this form:

[php] view plain copyArray (
[0] => Array

    (  
        [category_id] => 1  
        [category_name] => About me  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
    )  


[1] => Array  
    (  
        [category_id] => 2  
        [category_name] => Life Essays  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
    )  



[2] => Array  
    (  
        [category_id] => 3  
        [category_name] => Article Categories  
        [category_pid] => 0  
        [category_addtime] => 0  
        [category_order] => 0  
        [category_child] => Array  
            (  
                [0] => Array  
                    (  
                        [category_id] => 4  
                        [category_name] => Linux The server  
                        [category_pid] => 3  
                        [category_addtime] => -28800  
                        [category_order] => 1  
                        [category_child] => Array  
                            (  
                                [0] => Array  
                                    (  
                                        [category_id] => 5  
                                        [category_name] => linux optimization  
                                        [category_pid] => 4  
                                        [category_addtime] => 0  
                                        [category_order] => 0  
                                    )  


                                [1] => Array  
                                    (  
                                        [category_id] => 6  
                                        [category_name] => Virtualization  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478228220  
                                        [category_order] => 0  
                                    )  



                                [2] => Array  
                                    (  
                                        [category_id] => 7  
                                        [category_name] => Mysql Optimization and Development  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478188800  
                                        [category_order] => 0  
                                    )  

                                [3] => Array  

                                    (  
                                        [category_id] => 8  
                                        [category_name] => High Availability and Virtualization  
                                        [category_pid] => 4  
                                        [category_addtime] => 1478394120  
                                        [category_order] => 0  
                                    )  
                            )  
                    )  

                [1] => Array  
                    (  
                        [category_id] => 15  
                        [category_name] => Mysql  
                        [category_pid] => 3  
                        [category_addtime] => 1480555980  
                        [category_order] => 0  
                        [category_child] => Array  
                            (  
                                [0] => Array  
                                    (  
                                        [category_id] => 16  
                                        [category_name] => optimization  
                                        [category_pid] => 15  
                                        [category_addtime] => 1480555980  
                                        [category_order] => 0  
                                    )  
                                [1] => Array  
                                    (  
                                        [category_id] => 17  
                                        [category_name] => Sql programming  
                                        [category_pid] => 15  
                                        [category_addtime] => 1480556040  
                                        [category_order] => 8  
                                    )  
                            )  
                    )  
            )  
    )  

)

So how can we turn a two-dimensional array we take out of the database into one like this?
Give an example:

We want to implement the two-dimensional array below in the form above.

[php] view plain copy

$arr=array(

array('id'=>'1','name'=>'Beijing','pid'=>'0'),    

array('id'=>'2','name'=>'Shanghai','pid'=>'0'),    

array('id'=>'3','name'=>'Pudong','pid'=>'2'),    

array('id'=>'4','name'=>'Chaoyang','pid'=>'1'),    

array('id'=>'5','name'=>'Guangzhou','pid'=>'0'),    

array('id'=>'6','name'=>'Village','pid'=>'4'),   

array('id'=>'7','name'=>'Guangdong','pid'=>'5'),   

array('id'=>'8','name'=>'Sanli','pid'=>'4'),  

array('id'=>'10','name'=>'alley','pid'=>'8')  

);

First, use the same index of the array as the id number of the primary key to find subcolumns. First, add an index to the array:

[php] view plain copy

$arr=array(

1=>array('id'=>'1','name'=>'Beijing','pid'=>'0'),    

2=>array('id'=>'2','name'=>'Shanghai','pid'=>'0'),    

3=>array('id'=>'3','name'=>'Pudong','pid'=>'2'),    

4=>array('id'=>'4','name'=>'Chaoyang','pid'=>'1'),    

5=>array('id'=>'5','name'=>'Guangzhou','pid'=>'0'),    

6=>array('id'=>'6','name'=>'Village','pid'=>'4'),   

7=>array('id'=>'7','name'=>'Guangdong','pid'=>'5'),   

8=>array('id'=>'8','name'=>'Sanli','pid'=>'4'),  

10=>array('id'=>'10','name'=>'alley','pid'=>'8')  

);

Use indexed subscripts to determine if the column has a parent column, and if so, place the column in the son-child array of the parent column
[php] view plain copy

function generateTree($items){

$tree = array();  

foreach($items as $item){  

    //Determine if there is an index of the array==  

    if(isset($items[$item['pid']])){     //Find if there is this category in the array, such as isset ($items[0]) isset ($items[1])  

        $items[$item['pid']]['son'][] = &$items[$item['id']]; //As the content above changes, the value inside $tree changes  

    }else{  

        $tree[] = &$items[$item['id']];   //Give his address to $tree  

    }    

}  

return $tree;  

}

The main problem with this program above is that we added the index of the array manually?Can we automatically add an array index?Of course, the following program is implemented, automatically adding an index to the array and then putting the subcolumns into the son array of the parent column, thinking the same as the above program

[php] view plain copy

function make_tree(list,list,list,pk='id',pid=′pid′,pid=&#x27;pid&#x27;,pid=′pid′,child='_child',$root=0){

$tree=array();   

$packData=array();  

foreach ($list as  $data) {  
<span style="white-space:pre">    </span>//Convert to Array with Primary Key id  
    $packData[$data[$pk]] = $data; //$packData[1]=$data; $packData[2]=$data   
}  
foreach ($packData as $key =>$val){       
    if($val[$pid]==$root){   //Represents the following node         
        $tree[]=& $packData[$key];  
    }else{  
        //Find its parent  
        $packData[$val[$pid]][$child][]=& $packData[$key];  
    }  

}  
return $tree;  

}

Second method: use recursion to find subcolumns
Idea: Use recursion to find subcolumns in each column, and print until you find the last subcolumn and run debugging one more level out

Tree, for ease of understanding, you can print $tree to watch the array change

[php] view plain copy

array('id'=>'6','name'=>'Sanlitun','pid'=>'4'),

[php] view plain copyfunction make_tree1(list,list,list,pk='id',pid=′pid′,pid=&#x27;pid&#x27;,pid=′pid′,child='_child',$root=0){
tree=array();foreach(tree=array(); foreach(tree=array();foreach(list as $key=> $val){

    if($val[$pid]==$root){  
        //Get all subclasses of the current $pid   
            unset($list[$key]);  
            if(! empty($list)){  
                $child=make_tree1($list,$pk,$pid,$child,$val[$pk]); //Come here to find subcolumns in Beijing recursively empty  
                if(!empty($child)){  
                    $val['_child']=$child;  
                }  
            }                
            $tree[]=$val;  
    }  

}     

return $tree;  

}

To better understand recursion, you can find a small program to test, for example, this summation program
You can analyze the output of $n from 2,3...10, instead of 10, 9 - 2, I understand how recursion in that program above works. In a word, recursion is interesting and I hope you can understand it well.
[php] view plain copy

function sum($n){
a=0;if(a=0; if(a=0;if(n>1){
a=sum(a=sum(a=sum(n-1)+n;/∗if(n; /*if(n;/∗if(n>5){
echo "KaTeX parse error: Expected 'EOF', got '}' at position 22: …/>" ; }̲*/ ech…n
";
}else{
$a=1;
}
return $a;

}

echo sum(10);

Get data for all subclass id based on parent id

#$id = parent id, array = all taxonomies public function getSon(array = all taxonomies public function getSon(array = all taxonomies public function getSon (id, $array){

    static $list;        foreach ($array as $k => $v) {        
        if($v['parent_id'] == $id){      
                  $list[] = $array[$k];          
                        self::getSon($v['id'],$array);

        }

    }        return $list;

}

Topics: Programming PHP Linux MySQL Windows