这篇文章主要介绍了PHP递归写入MySQL实现无限级分类数据操作,涉及mysql数据库的创建以及php递归写入、读取数据库分类相关操作技巧,需要的朋友可以参考下
本文实例讲述了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);
Atas ialah kandungan terperinci PHP递归写入MySQL实现无限级分类数据操作示例_php技巧. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!