A Case Study of php infinitus classification and a case study of php Classification
Author: White Wolf Source: http://www.manks.top/php_tree_deep.html this article copyright to the author, welcome to reprint, but without the author's consent must retain this paragraph of the statement, and in the Article Page clearly given the original connection, otherwise, you are entitled to pursue legal liability. The original text contains images.
In normal development, the problem of infinitus classification is more or less inevitable, because efficiency, logic and other problems have always made these problems more acute. Today, we will take the yii2 framework as the basis and the topic infinitus as an example to give a simple solution to this problem.
First, we have a column data table tree.
Table Structure, for example, (the original text has a diagram)
It seems that the table structure is very simple.
Insert several test data records
INSERT INTO `tree` (`id`, `parent_id`, `name`) VALUES (1, 0, 'A'), (2, 0, 'B'), (3, 1, 'a'), (4, 3, 'aa'), (5, 2, 'b'), (6, 4, 'aaa');
The tree structure is roughly as follows:
|A |--a |----aa |------aaa |B |--b
This is exactly the data structure we need. Let's take a look at how to handle it to get the expected results.
We have also mentioned that yii2 is the basis, so our writing is also based on object-oriented rules.
Class tree {// access index to view the tree structure public function actionIndex () {$ data = self: getTree (); // to facilitate testing, here we output \ Yii: $ app-> response-> format = \ yii \ web \ Response: FORMAT_JSON; return $ data;} In json format ;} // retrieve the tree public static function getTree () {// here we get all the data directly, then, the most taboo in the infinitus classification is to perform layer-by-layer operations on the database, which can easily cause memory overflow. // Finally, the computer crashes. Result $ data = static :: find ()-> all (); return self: _ generateTree ($ data);} // generate tree private static function _ generateTree ($ data, $ pid = 0) {$ tree = []; if ($ data & is_array ($ data) {foreach ($ data as $ v) {if ($ v ['parent _ id'] = $ pid) {$ tree [] = ['id' => $ v ['id'], 'name' => $ v ['name'], 'parent _ id' => $ v ['parent _ id'], 'Children '=> self :: _ generateTree ($ data, $ v ['id']),] ;}}return $ tree ;}}
Let's look at the tree/index below, as shown below:
In this way, we can see a clear tree structure, which is what we ultimately need.