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

时间:2022-06-17 11:08:27

本文实例讲述了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程序设计有所帮助。