今天主要介紹一下使用遞歸來按層級查找數(shù)據(jù)。
原理挺簡單的,主要是通過父級id一級一級的循環(huán)查找子級,使用PHP循環(huán)代碼也很容易實現(xiàn),不過如果層級越多,PHP重復代碼也越多,這時可以使用遞歸來實現(xiàn)這功能。
1、首先查出要使用的數(shù)據(jù)組成一個數(shù)組(避免遞歸里查詢數(shù)據(jù)庫,之后根據(jù)這個數(shù)組組成自己需要的數(shù)據(jù)就可以了)
比如得到如下數(shù)據(jù):
$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、接下來使用遞歸重組數(shù)據(jù),使數(shù)據(jù)按層級顯示。
/** * 根據(jù)父級id查找子級數(shù)據(jù) * @param $data 要查詢的數(shù)據(jù) * @param int $pid 父級id */ public function recursion($data, $pid = 0) { static $child = []; // 定義存儲子級數(shù)據(jù)數(shù)組 foreach ($data as $key => $value) { if ($value['pid'] == $pid) { $child[] = $value; // 滿足條件的數(shù)據(jù)添加進child數(shù)組 unset($data[$key]); // 使用過后可以銷毀 $this->recursion($data, $value['id']); // 遞歸調(diào)用,查找當前數(shù)據(jù)的子級 } } return $child; }
得到結(jié)果:
[ { "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" } ]
3、還可以使用下面的方法,顯示更有層次感。
/** * 根據(jù)父級id查找子級數(shù)據(jù) * @param $data 要查詢的數(shù)據(jù) * @param int $pid 父級id */ public function recursion($data, $pid = 0) { $child = []; // 定義存儲子級數(shù)據(jù)數(shù)組 foreach ($data as $key => $value) { if ($value['pid'] == $pid) { unset($data[$key]); // 使用過后可以銷毀 $value['child'] = $this->recursion($data, $value['id']); // 遞歸調(diào)用,查找當前數(shù)據(jù)的子級 $child[] = $value; // 把子級數(shù)據(jù)添加進數(shù)組 } } return $child; }
得到結(jié)果:
[ { "id": "1", "pid": "0", "dsp": "1", "child": [ { "id": "4", "pid": "1", "dsp": "1-4", "child": [ { "id": "5", "pid": "4", "dsp": "1-4-5", "child": [ { "id": "6", "pid": "5", "dsp": "1-4-5-6", "child": [] } ] }, { "id": "10", "pid": "4", "dsp": "1-4-10", "child": [] } ] }, { "id": "9", "pid": "1", "dsp": "1-9", "child": [] } ] }, { "id": "2", "pid": "0", "dsp": "2", "child": [ { "id": "8", "pid": "2", "dsp": "2-8", "child": [] } ] }, { "id": "3", "pid": "0", "dsp": "3", "child": [ { "id": "7", "pid": "3", "dsp": "3-7", "child": [] } ] } ]