Classification technology developed in PHP uses foreach loop to implement classification function
What is classification? Just like creating a new folder under Windows, you can create a new
folder under the newly created folder. This will continue in an infinite loop. The same is true for classification. The parent class can be divided into subclasses, and the subclasses
Can be divided into its subcategories. . . . . .
How does PHP implement its classification? How to list its various categories one by one?
In this chapter we will introduce the use of foreach loop to implement the classification function.
First build a classification array:
<?php $categories = array( array('id'=>1,'name'=>'电脑','pid'=>0), array('id'=>2,'name'=>'手机','pid'=>0), array('id'=>3,'name'=>'笔记本','pid'=>1), array('id'=>4,'name'=>'台式机','pid'=>1), array('id'=>5,'name'=>'智能机','pid'=>2), array('id'=>6,'name'=>'功能机','pid'=>2), array('id'=>7,'name'=>'超级本','pid'=>3), array('id'=>8,'name'=>'游戏本','pid'=>3), ); ?>
There are 3 fields here, sorting id, classification name name, and classification pid
The goal is to convert it into the following Structure:
<?php array( //1对应$categories中的id ,方便直接读取 1 => array( 'id'=>1, 'name'=>'电脑', 'pid'=>0, 'children' =>array( array( 'id'=>3, 'name'=>'笔记本', 'pid'=>1, 'children'=>array( 'id'=>7, 'name'=> '超极本', 'pid'=>'3' ), array( 'id'=>8, 'name'=> '游戏本', 'pid'=>'3' ) , ), array( 'id'=>4, 'name'=>'台式机', 'pid'=>1, ), ), ), 2 => array( 'id'=>2, 'name'=>'手机', 'pid'=>0, 'children' =>array( array( 'id'=>5, 'name'=>'智能机', 'pid'=>2, ), array( 'id'=>6, 'name'=>'功能机', 'pid'=>2, ), ), ), ); ?>
Implementation process:
Create an empty array
<?php $tree = array(); ?>
The first step is to add all classification ids As the array key, and create the children unit
<?php foreach($categories as $category){ $tree[$category['id']] = $category; $tree[$category['id']]['children'] = array(); } ?>
The second step is to use references to add each category to the parent class children array, so that a tree structure can be formed in one traversal.
<?php foreach ($tree as $key=>$value) { if ($value['pid'] != 0) { $tree[$value['pid']]['children'][] = $tree[$key]; } } ?>
Finally use print_r(); to print it out
<?php print_r($tree); ?>
Advantages: The relationship is clear, and it is simple to modify the superior-subordinate relationship.
Disadvantages: Using PHP processing, if the number of categories is large, the efficiency will also be reduced.