城市无限分类方法及设计数据库

 public function regionCity(){

        $cacheKey = 'region_city_cache';
        $data = Cache::get($cacheKey);
        if( empty($data))   {
            $city = RegionCity::where('id','>', 0)->select('id','name','parentId')->get()->toArray();
            $data = $this->tree($city);
            Cache::put($cacheKey, $data,60*24);
        }
        return response()->json(['code'=>'0000','data'=>$data]);
    }


    /**
     * 将地区的数据,整理成树状结构
     * @param $data
     * @param int $pid
     * @return array
     */
    private function tree ($data, $pid = 0) {
        $return = array();
        foreach($data as $tree) {
            if($tree['parentId'] == $pid) {
                foreach($data as $subtree) {
                    if($subtree['parentId'] == $tree['id']) {
                        $tree['child'] = self::tree($data, $tree['id']);
                        break;
                    }
                }
                $return[] = $tree;
            }
        }
        return $return;
    }

 表结构

-- ----------------------------
-- Table structure for region_city
-- ----------------------------
DROP TABLE IF EXISTS `region_city`;
CREATE TABLE `region_city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL,
`name` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL,
`parentId` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3442 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='地区';

 

posted on 2022-08-08 14:57  kevin_yang123  阅读(28)  评论(0编辑  收藏  举报