In peacetime development of more or less inevitably encounter infinite pole classification problem, because the efficiency, logic and other problems have always made this kind of problem is more acute. Today we take the YII2 framework as the foundation, the column infinite Extremely example, carries on a simple processing to this question.
First we have a column data table tree
The table structure is as follows (original diagram)
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 the type of data structure we need, so let's see how we can get the results we need.
We also said earlier, based on Yii2, so our writing is also according to the object-oriented rules
Class Tree {
//Access Index View the TreeView structure public
function Actionindex () {
$data = Self::gettree ();
For convenience of testing, we output \yii in JSON format
:: $app->response->format = \yii\web\response::format_json;
return $data;
}
Get the tree public
static function Gettree () {
//Here we get all the data directly, and then process it
////////In the infinite Pole classification, the most taboo is to layer the database. It is also 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 ' => $v [' name '],
' parent_id ' => $v [' parent_id '],
' children ' => Self::_generatetree ($data, $v [' id ']),
];
}} return $tree;
}
We visit the next tree/index to see the effect of the following map
So we can see a very clear tree-shaped chart, which is what we ultimately need.
About PHP infinite Pole classification of the case tutorial to introduce so many people, I hope to help you!