php 无限级分类,超级简单的无限级分类,支持输出树状图
返回一维数组
//无限级分类
function GetTree($arr, $pid = 0, $step = 0)
{
static $tree;
foreach ($arr as $key => $val) {
if ($val['pid'] == $pid) {
$name = isset($val['title']) ? $val['title'] : $val['name'];
$flg = str_repeat('┗━ ', $step);
$val['tag'] = $flg . $name;
$val['level'] = $step;
$tree[] = $val;
GetTree($arr, $val['id'], $step + 1);
}
}
return $tree;
}
返回多维数组
/**
* @param $items [需要处理的数组]
* @return array [多维数组]
*/
function generateTree($items)
{
$tree = array();
$tmp1 = array();
foreach ($items as $key => $val) {
$tmp1[$val['id']] = &$items[$key];
}
foreach ($tmp1 as $item) {
if (isset($tmp1[$item['pid']])) {
$tmp1[$item['id']]['level'] += 1;
$tmp1[$item['id']]['tag'] = str_repeat('┗━ ', $tmp1[$item['id']]['level']) . $tmp1[$item['id']]['title'];
$tmp1[$item['pid']]['son'][] = &$tmp1[$item['id']];
} else {
$tmp1[$item['id']]['level'] = 0;
$tree[] = &$tmp1[$item['id']];
}
}
return $tree;
}
查询数组pid以下所有子树ID
function getDepUserTree($arr, $pid = 0)
{
static $tree;
foreach ($arr as $key => $val) {
if ($val['father'] == $pid) {
$tree[] = $val['id'];
getDepUserTree($arr, $val['id']);
}
}
return $tree;
}