這篇文章主要介紹了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);