A case of PHP infinite pole classification, PHP classification case
Author: White Wolf Source: http://www.manks.top/php_tree_deep.html This article copyright belongs to the author, welcome reprint, but without the author consent must retain this paragraph statement, and in the article page obvious location gives the original text connection, otherwise reserves the right to pursue legal responsibility. There are pictures in the original.
At ordinary times the development of more or less inevitably encounter the problem of infinite pole classification, because the efficiency, logic and other issues have been making such problems more acute. Today we take the YII2 framework as the foundation, the column infinite Extremely example, carries on the simple processing to this question.
First we have a column data table tree
Table structure (original image)
It seems that the table structure is simple.
We insert a few test data
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 what we need in the form of data structures, so let's look at how to handle it to get the results we need.
As we have said before, it is based on YII2, so our writing is also based on object-oriented rules.
Class Tree {//Access index view tree structure public Function actionindex () {$data = Self::gettree (); For the convenience of testing, here we output \yii in JSON format:: $app->response->format = \yii\web\response::format_json; return $data; }//Get tree public static function Gettree () {//Here we get all the data directly, and then process it through the program//the most taboo in the infinite pole classification is the layer operation of the database, also It is easy to cause memory overflow//Last computer crash results $data = Static::find ()->all (); Return Self::_generatetree ($data); }//Spanning 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 ' and ' = ' $v [' name ' ], ' parent_id ' = $v [' parent_id '], ' children ' and Self::_generatetree ($data, $v [' id ']),]; }}} return $tree; } }
We visit the next tree/index to see below
So we can see a very clear tree structure, which is what we need in the end.
http://www.bkjia.com/PHPjc/1125076.html www.bkjia.com true http://www.bkjia.com/PHPjc/1125076.html techarticle a case of PHP infinite pole classification, PHP classification case author: White Wolf Source: http://www.manks.top/php_tree_deep.html This article copyright to the author, welcome reprint, but without the author's consent must ...