无限极分类不是用递归 两个函数解决 新增和循环【附上代码】

实现无限极分类

首先先看一下数据结构

//数据结构
// $items = array(
//     1 => array('id' => 1, 'pid' => 0, 'name' => 'anhui'),
//     2 => array('id' => 2, 'pid' => 0, 'name' => 'zhejiang'),
//     3 => array('id' => 3, 'pid' => 1, 'name' => 'hefei'),
//     4 => array('id' => 4, 'pid' => 3, 'name' => 'zhangfeng'),
//     5 => array('id' => 5, 'pid' => 1, 'name' => 'anqing'),
//     6 => array('id' => 6, 'pid' => 0, 'name' => 'sichuan'),
//     7 => array('id' => 7, 'pid' => 0, 'name' => 'dayang'),
//     8 => array('id' => 8, 'pid' => 3, 'name' => 'guangdong'),
// );

以上的是数据结构 items表一共有三个字段 id自增  pid为0代表最顶级分类 name分类名称

//显示树结构
function generateTree($items){
    $tree = array();
    foreach($items as $item){
        if(isset($items[$item['pid']])){
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        }else{
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}

//新增子分类
function addtree(&$arr,$pid,$name){
    $num=count($arr)+1;
    if($num==0){$num=0;}
    $arr[$num]=array(
        'id'=>$num,
        'pid'=>$pid,
        'name'=>$name
    );
}
两个方法 addtree用来新增 genrateTree用来排序返回一个数组

以下附上完整代码

$num,
        'pid'=>$pid,
        'name'=>$name
    );
}


$items=array();
//数据结构
// $items = array(
//     1 => array('id' => 1, 'pid' => 0, 'name' => 'anhui'),
//     2 => array('id' => 2, 'pid' => 0, 'name' => 'zhejiang'),
//     3 => array('id' => 3, 'pid' => 1, 'name' => 'hefei'),
//     4 => array('id' => 4, 'pid' => 3, 'name' => 'zhangfeng'),
//     5 => array('id' => 5, 'pid' => 1, 'name' => 'anqing'),
//     6 => array('id' => 6, 'pid' => 0, 'name' => 'sichuan'),
//     7 => array('id' => 7, 'pid' => 0, 'name' => 'dayang'),
//     8 => array('id' => 8, 'pid' => 3, 'name' => 'guangdong'),
// );

addtree($items,'0','成都');
addtree($items,'1','自贡');
addtree($items,'2','富顺');
addtree($items,'0','上海');
addtree($items,'4','外滩');
addtree($items,'3','市中花园');
addtree($items,'3','福州花园');
// showtree($items);
print_r(generateTree($items));


?>


你可能感兴趣的:(无限极分类,后端)