<?php header("Content-type: text/html; charset=utf-8"); $arr = array( 0=>array('Id'=>1,'Name'=>'文件管理','Pid'=>0), 1=>array('Id'=>2,'Name'=>'來源管理','Pid'=>0), 2=>array('Id'=>3,'Name'=>'文件添加','Pid'=>1), 3=>array('Id'=>4,'Name'=>'文件刪除','Pid'=>1), 4=>array('Id'=>5,'Name'=>'人員列表','Pid'=>2), 5=>array('Id'=>6,'Name'=>'添加用戶','Pid'=>5), 6=>array('Id'=>7,'Name'=>'編輯用戶','Pid'=>5), ); function getTree($arr, $pid=0,$deep=0) { static $tree = array(); foreach($arr as $k=>$row) { if( $row['Pid'] == $pid ) { $row['deep'] = $deep; $tree[] = $row; unset($arr[$k]); getTree($arr,$row['Id'],$deep+1); } } return $tree; } $res = getTree($arr); echo "<pre>"; print_r($res);
運行結果: