数据结构:category(id, pid, name),对应:信息ID,父项ID,类别名
测试数据:
$aryCate = array(
array('id' => 1, 'pid' => 0, 'name' => 'Level0'),
array('id' => 2, 'pid' => 1, 'name' => 'Level0_1'),
array('id' => 3, 'pid' => 2, 'name' => 'Level0_1_1'),
array('id' => 4, 'pid' => 3, 'name' => 'Level0_1_1_1'),
array('id' => 5, 'pid' => 3, 'name' => 'Level0_1_1_2'),
array('id' => 6, 'pid' => 0, 'name' => 'Level0'),
array('id' => 7, 'pid' => 6, 'name' => 'Level0_2'),
array('id' => 8, 'pid' => 7, 'name' => 'Level0_2_1'),
array('id' => 9, 'pid' => 8, 'name' => 'Level0_2_1_1'),
array('id' => 10, 'pid' => 8, 'name' => 'Level0_2_1_2'),
array('id' => 11, 'pid' => 0, 'name' => 'Level0'),
array('id' => 12, 'pid' => 11, 'name' => 'Level0_3'),
array('id' => 13, 'pid' => 12, 'name' => 'Level0_3_1'),
array('id' => 14, 'pid' => 13, 'name' => 'Level0_3_1_1'),
array('id' => 15, 'pid' => 13, 'name' => 'Level0_3_1_2'),
array('id' => 16, 'pid' => 0, 'name' => 'Level0'),
array('id' => 17, 'pid' => 1, 'name' => 'Level0_2'),
);
+++++++++++++++++++++++++++++
代码:
/**
* 利用递归法获取无限极类别的树状数组
* @param array $ary 数据库读取数组
* @param int $pid 父级ID(顶级类别的pid为0)
* @param int $level 返回的树状层级
* @param int $i 层级起始值
* @return array 返回树状数组
*/
function aryTree($ary = array(), $pid = 0, $level = 10, $i = 1){
$arr = array();
foreach($ary as $rs){
if($rs['pid'] == $pid){
if($i <= $level){
$arr[$rs['id']] = $rs;
}else{
break;
}
$n = $i;
$n++;
$sub = aryTree($ary, $rs['id'], $level, $n);
empty($sub) OR $arr[$rs['id']]['sub'] = $sub;
}else{
continue;
}
}
return $arr;
}