本文實例講述了PHP遞歸寫入MySQL實現(xiàn)無限級分類數(shù)據(jù)操作。分享給大家供大家參考,具體如下:
PHP遞歸寫入MySQL無限級分類數(shù)據(jù),表結(jié)構(gòu):
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); // 獲取數(shù)據(jù) $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); // 插入數(shù)據(jù)庫,得到父ID self::addCategoryFromKepler($value['id'], $parentid_sub); // 遞歸 } } return true; }
調(diào)用代碼:
KeplerCategory::addCategoryFromKepler(0);
遞歸方法讀取代碼:
static public function getCategoryFormatToKepler($parentid, $format_data = array(), $parent_prefix = '', $current_prefix = ''){ $category_list = self::getCategoryByParentid($parentid); // 根據(jù)父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; }
調(diào)用代碼:
$category_list = KeplerCategory::getCategoryFormatToKepler(0);
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《php+mysqli數(shù)據(jù)庫程序設計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
下一篇:PHP快速排序算法實例分析