无限级分类

  1. $array = [
  2. ['id' => 1, 'pid' => 0, 'name' => '河南省'],
  3. ['id' => 2, 'pid' => 0, 'name' => '山东省'],
  4. ['id' => 3, 'pid' => 0, 'name' => '四川省'],
  5. ['id' => 4, 'pid' => 1, 'name' => '郑州市'],
  6. ['id' => 5, 'pid' => 1, 'name' => '开封市'],
  7. ['id' => 6, 'pid' => 4, 'name' => '金水区'],
  8. ['id' => 7, 'pid' => 5, 'name' => '兰考县'],
  9. ];

 

 

<?php
namespace app\index\controller;

use think\Db;


class Fenlei
{

function index()
{
$arr = Db::name('test')->select();

$refer = [];
$tree = [];
foreach ($arr as $k => $v) {
$refer[$v['id']] = & $arr[$k];
}
foreach ($arr as $k => $v) {
$pid = $v['pid'];
if ($pid == 0) {
$tree[] = & $arr[$k];
} else {
if (isset($refer[$pid])) {
$refer[$pid]['subcat'][] = & $arr[$k];
}
}
}

echo '<pre>';
var_dump($tree);
}

 

}

posted @ 2022-05-31 15:30  79524795  阅读(23)  评论(0编辑  收藏  举报