php 无限分类递归树形代码优化

参考文章链接

https://blog.csdn.net/jayhkw/article/details/68947135 

https://www.cnblogs.com/walblog/articles/8315732.html

 

优化后代码

将数据重组封装到了生成树里面,可以解决ID乱序有bug的问题 

都是先整理数组,再格式化成树形结构

只是代码稍微简洁了一点点,没有本质上的差别


/**
 * 根据地址名称匹配商城地址id
 */
function area_list_by_ru($pid = 0, $ru_id='', &$lists = array()) { 
    if ($ru_id!='') {
        $where .= " rs.suser_id = $ru_id";
    }    
    $sql = "SELECT rs.code id,rs.id rsid,rs.name,rs.parent_id pid, rs.region_id,r.region_name" .
                " FROM " .$GLOBALS['ecs']->table('region_seller') ." as rs ".
                "LEFT JOIN " . $GLOBALS['ecs']->table('region') . " r on r.region_id = rs.region_id " .
                " WHERE ".$where;
    $list = $GLOBALS['db']->getAll($sql);   
    return genTree($list);
}
  
/**
 * 将数据格式化成树形结构
 * @author juan
 * @param array $items 原始数据
 * @return array 格式化后的树形结构
 */
function genTree($items,$pid ="pid") {

    $map  = [];
    $tree = [];   
    foreach ($items as &$it){ $map[$it['id']] = &$it; }  //先整理一下数组以数据的ID名生成新的引用索引树
    foreach ($map as &$item){//将数据格式化成树形结构
        $map[$item['pid']]['son'][$item['id']] = &$map[$item['id']];        
    }
    return isset($map[0]['son']) ? $map[0]['son'] : array();
}

 优化前代码


/**
 * 根据地址名称匹配商城地址id
 */
function area_list_by_ru($pid = 0, $ru_id='', &$lists = array()) { 
    if ($ru_id!='') {
        $where .= " rs.suser_id = $ru_id";
    }    
    $sql = "SELECT rs.code id,rs.id rsid,rs.name,rs.parent_id pid, rs.region_id,r.region_name" .
                " FROM " .$GLOBALS['ecs']->table('region_seller') ." as rs ".
                "LEFT JOIN " . $GLOBALS['ecs']->table('region') . " r on r.region_id = rs.region_id " .
                " WHERE ".$where;
    $list = $GLOBALS['db']->getAll($sql);
   
    //先整理一下数组以code为键
    $return = [];
    foreach ($list as $v){
        $return[$v['id']] = [
            'id' => $v['id'],
            'name' => $v['name'],
            'rsid' => $v['rsid'],
            'pid' => $v['pid'],
            'region_id' => $v['region_id'],
            'region_name' => $v['region_name'],
        ];
    }
       
    return genTree($return);
}
  
/**
 * 将数据格式化成树形结构
 * @author juan
 * @param array $items 原始数据
 * @return array 格式化后的树形结构
 */
function genTree($items) {
    foreach ($items as $item){
        $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];        
    }
    return isset($items[0]['son']) ? $items[0]['son'] : array();
}
  

 

 

你可能感兴趣的:(PHP)