數組:
復制代碼 代碼如下:
$items = array(
array('id' => 1, 'pid' => 0, 'name' => '一級11' ),
array('id' => 11, 'pid' => 0, 'name' => 'www.jb51.net 一級12' ),
array('id' => 2, 'pid' => 1, 'name' => '二級21' ),
array('id' => 10, 'pid' => 11, 'name' => '二級22' ),
array('id' => 3, 'pid' => 1, 'name' => '二級23' ),
array('id' => 12, 'pid' => 11, 'name' => '二級24' ),
array('id' => 13, 'pid' => 12, 'name' => '三級31' ),
array('id' => 9, 'pid' => 1, 'name' => '二級25' ),
);
函數:
復制代碼 代碼如下:
function formatTree($array, $pid = 0){
$arr = array();
$tem = array();
foreach ($array as $v) {
if ($v['pid'] == $pid) {
$tem = formatTree($array, $v['id']);
//判斷是否存在子數組
$tem && $v['son'] = $tem;
$arr[] = $v;
}
}
return $arr;
}