PHP uses recursion to find data hierarchically

Today I'll focus on using recursion to find data hierarchically.The principle is very simple. It is mainly to find the children through the paren...

Today I'll focus on using recursion to find data hierarchically.
The principle is very simple. It is mainly to find the children through the parent id level loop. It is also easy to use PHP loop code. However, if there are more levels, there will be more duplicate PHP code. In this case, you can use recursion to achieve this function.

1. First find out the data to be used to form an array (avoid querying the database recursively, and then make up the data you need according to the array)
For example, the following data are obtained:

$data = [ ['id' => '1', 'pid' => '0', 'dsp' => '1'], ['id' => '2', 'pid' => '0', 'dsp' => '2'], ['id' => '3', 'pid' => '0', 'dsp' => '3'], ['id' => '4', 'pid' => '1', 'dsp' => '1-4'], ['id' => '5', 'pid' => '4', 'dsp' => '1-4-5'], ['id' => '6', 'pid' => '5', 'dsp' => '1-4-5-6'], ['id' => '7', 'pid' => '3', 'dsp' => '3-7'], ['id' => '8', 'pid' => '2', 'dsp' => '2-8'], ['id' => '9', 'pid' => '1', 'dsp' => '1-9'], ['id' => '10', 'pid' => '4', 'dsp' => '1-4-10'], ];

2. Next, use recursion to reorganize the data so that the data can be displayed hierarchically.

/** * Find child data based on parent id * @param $data Data to query * @param int $pid Parent id */ public function recursion($data, $pid = 0) { static $child = []; // Define storage child data array foreach ($data as $key => $value) { if ($value['pid'] == $pid) { $child[] = $value; // Data that meets the conditions is added to the child array unset($data[$key]); // Can be destroyed after use $this->recursion($data, $value['id']); // Recursive call to find the children of the current data } } return $child; }

Results:

[ { "id": "1", "pid": "0", "dsp": "1" }, { "id": "4", "pid": "1", "dsp": "1-4" }, { "id": "5", "pid": "4", "dsp": "1-4-5" }, { "id": "6", "pid": "5", "dsp": "1-4-5-6" }, { "id": "10", "pid": "4", "dsp": "1-4-10" }, { "id": "9", "pid": "1", "dsp": "1-9" }, { "id": "2", "pid": "0", "dsp": "2" }, { "id": "8", "pid": "2", "dsp": "2-8" }, { "id": "3", "pid": "0", "dsp": "3" }, { "id": "7", "pid": "3", "dsp": "3-7" } ]

10 November 2019, 14:34 | Views: 5176

Add new comment

For adding a comment, please log in
or create account

0 comments