递归部门
部門有子部門,子部門又有子部分,后代部門無限制,數據庫儲存結構如datalist,通常需要構造成層次結構。
<?php$deptlist = [['id'=>'1','name'=>'名稱1','pid'=>'0'],['id'=>'2','name'=>'名稱2','pid'=>'1'],['id'=>'3','name'=>'名稱3','pid'=>'1'],['id'=>'4','name'=>'名稱4','pid'=>'3'],['id'=>'5','name'=>'名稱5','pid'=>'3'],['id'=>'6','name'=>'名稱6','pid'=>'5'],['id'=>'7','name'=>'名稱7','pid'=>'5'],['id'=>'8','name'=>'名稱8','pid'=>'0'],['id'=>'9','name'=>'名稱9','pid'=>'8'],['id'=>'10','name'=>'名稱10','pid'=>'8'], ];function getDeptbyPid($arr,$pid){$filtered = array_filter($arr, function($item) use ($pid) {return $item['pid'] == $pid;});return $filtered;}$topdepts = getDeptbyPid($deptlist,'0');foreach ($topdepts as &$v){$v['son'] = getSonDept($deptlist,$v['id']); }function getSonDept($arr,$pid){$dpets = getDeptbyPid($arr,$pid);foreach ($dpets as &$v){$v['son'] = getSonDept($arr,$v['id']);}return $dpets; }print_r($topdepts);結果
{"0": {"id": "1","name": "名稱1","pid": "0","son": {"1": {"id": "2","name": "名稱2","pid": "1","son": []},"2": {"id": "3","name": "名稱3","pid": "1","son": {"3": {"id": "4","name": "名稱4","pid": "3","son": []},"4": {"id": "5","name": "名稱5","pid": "3","son": {"5": {"id": "6","name": "名稱6","pid": "5","son": []},"6": {"id": "7","name": "名稱7","pid": "5","son": []}}}}}}},"7": {"id": "8","name": "名稱8","pid": "0","son": {"8": {"id": "9","name": "名稱9","pid": "8","son": []},"9": {"id": "10","name": "名稱10","pid": "8","son": []}}} }?
其中
$topdepts = getDeptbyPid($deptlist,'0');foreach ($topdepts as &$v){$v['son'] = getSonDept($deptlist,$v['id']); }可以簡化為
getSonDept($deptlist,'0')?
轉載于:https://www.cnblogs.com/jimzbom/p/7790368.html
總結
- 上一篇: DOM性能瓶颈与Javascript性能
- 下一篇: ORM框架之------Dapper,N