PHP递归写入MySQL实现无限级分类数据操作示例

PHP递归写入MySQL无限级分类数据,表结构:

CREATE TABLE `kepler_goods_category` ( `id` int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, `parentid` int unsigned NOT NULL default 0 comment '父级分类ID', `name` varchar(255) NOT NULL default '' comment '分类名称', `kepler_fid` int unsigned NOT NULL default 0 comment '对应开普勒分类ID', `create_time` timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

递归方法写入代码:

static public function addCategoryFromKepler($fid, $parentid = 0){ $category_list = Kepler::queryGoodsCategoryList($fid); // 获取数据 $category_list = $category_list['jd_kepler_item_querycategoriesbyfid_response']; if($category_list['total'] > 0){ foreach ($category_list['categories'] as $key => $value) { $parentid_sub = KeplerCategory::addCategory($value['name'], $value['id'], $parentid); // 插入数据库,得到父ID self::addCategoryFromKepler($value['id'], $parentid_sub); // 递归 } } return true; }

调用代码:

KeplerCategory::addCategoryFromKepler(0);

递归方法读取代码:

static public function getCategoryFormatToKepler($parentid, $format_data = array(), $parent_prefix = '', $current_prefix = ''){ $category_list = self::getCategoryByParentid($parentid); // 根据父ID获取 if(!empty($category_list)){ foreach ($category_list as $key => $value) { $format_data = self::getCategoryFormatToKepler($value['id'], $format_data, $parent_prefix . ',' . $current_prefix, $value['kepler_fid']); } }else{ $format_data[] = trim($parent_prefix . ',' . $current_prefix, ','); } return $format_data; }

调用代码:

$category_list = KeplerCategory::getCategoryFormatToKepler(0);

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/068736bc425b8bd4eb7276c79adc7cc6.html