PHP recursively writes MySQL to realize infinite level classification data operation example

  • 2021-10-25 06:06:09
  • OfStack

In this paper, an example is given to describe the recursive writing of PHP to MySQL to realize infinite classification data operation. Share it for your reference, as follows:

PHP recursively writes MySQL infinite class data, table structure:


CREATE TABLE `kepler_goods_category` (
 `id` int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
 `parentid` int unsigned NOT NULL default 0 comment ' Parent classification ID',
 `name` varchar(255) NOT NULL default '' comment ' Classification name ',
 `kepler_fid` int unsigned NOT NULL default 0 comment ' Corresponding Kepler classification ID',
 `create_time` timestamp NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Recursive method writes code:


static public function addCategoryFromKepler($fid, $parentid = 0){
  $category_list = Kepler::queryGoodsCategoryList($fid); //  Get data 
  $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); //  Insert the database to get the parent ID
      self::addCategoryFromKepler($value['id'], $parentid_sub); //  Recursion 
    }
  }
  return true;
}

Calling code:


KeplerCategory::addCategoryFromKepler(0);

Recursive method reads code:


static public function getCategoryFormatToKepler($parentid, $format_data = array(), $parent_prefix = '', $current_prefix = ''){
  $category_list = self::getCategoryByParentid($parentid); //  According to the parent ID Get 
  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;
}

Calling code:


$category_list = KeplerCategory::getCategoryFormatToKepler(0);

For more readers interested in PHP related contents, please check the topics on this site: "Introduction to php+mysql Database Operation", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: