PHP递归实现无限级分类的代码示例

  <?php

  // 模拟分类数据

  $categories = array(

  array('id' => 1, 'name' => '电子产品', 'parent_id' => 0),

  array('id' => 2, 'name' => '手机', 'parent_id' => 1),

  array('id' => 3, 'name' => '笔记本电脑', 'parent_id' => 1),

  array('id' => 4, 'name' => '家用电器', 'parent_id' => 0),

  array('id' => 5, 'name' => '电视', 'parent_id' => 4),

  array('id' => 6, 'name' => '冰箱', 'parent_id' => 4),

  array('id' => 7, 'name' => '空调', 'parent_id' => 4),

  array('id' => 8, 'name' => '服饰', 'parent_id' => 0),

  array('id' => 9, 'name' => '男装', 'parent_id' => 8),

  array('id' => 10, 'name' => '女装', 'parent_id' => 8),

  array('id' => 11, 'name' => '鞋类', 'parent_id' => 0),

  array('id' => 12, 'name' => '男鞋', 'parent_id' => 11),

  array('id' => 13, 'name' => '女鞋', 'parent_id' => 11),

  array('id' => 14, 'name' => '数码产品', 'parent_id' => 1),

  array('id' => 15, 'name' => '相机', 'parent_id' => 14),

  array('id' => 16, 'name' => '摄像机', 'parent_id' => 14),

  array('id' => 17, 'name' => '办公用品', 'parent_id' => 0),

  array('id' => 18, 'name' => '文具', 'parent_id' => 17),

  array('id' => 19, 'name' => '办公设备', 'parent_id' => 17),

  array('id' => 20, 'name' => '电脑配件', 'parent_id' => 1),

  array('id' => 21, 'name' => '显示器', 'parent_id' => 20),

  array('id' => 22, 'name' => '内存条', 'parent_id' => 20),

  array('id' => 23, 'name' => '游戏机', 'parent_id' => 1),

  array('id' => 24, 'name' => 'PS5', 'parent_id' => 23),

  array('id' => 25, 'name' => 'Switch', 'parent_id' => 23),

  );

  // 递归处理分类数据

  function buildTree($categories, $parent_id = 0) {

  $tree = array();

  foreach ($categories as $category) {

  if ($category['parent_id'] == $parent_id) {

  $children = buildTree($categories, $category['id']);

  if ($children) {

  $category['children'] = $children;

  }

  $tree[] = $category;

  }

  }

  return $tree;

  }

  // 构建树形结构

  $tree = buildTree($categories);

  // 显示分类数据

  function showTree($tree, $indent = 0) {

  foreach ($tree as $category) {

  echo str_repeat("--", $indent) . $category['name'] . "
";

  if (isset($category['children'])) {

  showTree($category['children'], $indent + 1);

  }

  }

  }

  // 调用函数显示树形结构

  showTree($tree);

您可能感兴趣的文章:

相关文章