PHP实现无限级分类的方法
9
// get_tree_option()返回数组,并为每个元素增加了“深度”(即depth)列,直接输出即可
$options = get_tree_option($list, 1);
foreach($options as $op) {
echo '' . str_repeat(" ", $op['depth'] * 4) . $op['title'] . '';
}
?>
5. 查找某一分类的所有子类
4
$children = get_tree_child($list, 0);
echo implode(',', $children); // 输出:1,3,2,7,6,5,8,4
?>
6. 查找某一分类的所有父类
$children = get_tree_parent($list, 4);
echo implode(',', $children); //8, 2, 10
?>
7. 相关函数
180
function get_tree_child($data, $fid) {
$result = array();
$fids = array($fid);
do {
$cids = array();
$flag = false;
foreach($fids as $fid) {
for($i = count($data) - 1; $i >=0 ; $i--) {
$node = $data[$i];
if($node['fid'] == $fid) {
array_splice($data, $i , 1);
$result[] = $node['id'];
$cids[] = $node['id'];
$flag = true;
}
}
}
$fids = $cids;
} while($flag === true);
return $result;
}
function get_tree_parent($data, $id) {
$result = array();
$obj = array();
foreach($data as $node) {
$obj[$node['id']] = $node;
}
$value = isset($obj[$id]) ? $obj[$id] : null;
while($value) {
$id = null;
foreach($data as $node) {
if($node['id'] == $value['fid']) {
$id = $node['id'];
$result[] = $node['id'];
break;
}
}
if($id === null) {
$result[] = $value['fid'];
}
$value = isset($obj[$id]) ? $obj[$id] : null;
}
unset($obj);
return $result;
}
function get_tree_ul($data, $fid) {
$stack = array($fid);
$child = array();
$added_left = array();
$added_right= array();
$html_left = array();
$html_right = array();
$obj = array();
$loop = 0;
foreach($data as $node) {
$pid = $node['fid'];
if(!isset($child[$pid])) {
$child[$pid] = array();