前两天写功能的时候、写到无限级分类,其实没什么好记载的,主要是记录一个匿名函数的写法。非匿名函数调用在进程结束前重复使用会出现报错,函数已声明的错误

$arr = array(
  array('id' => 1, 'name' => '时事新闻', 'pid' => 0, 'level' => 0),
  array('id' => 2, 'name' => '体育新闻', 'pid' => 0, 'level' => 0),
  array('id' => 3, 'name' => '国内新闻', 'pid' => 1, 'level' => 1),
  array('id' => 4, 'name' => '足球新闻', 'pid' => 2, 'level' => 1),
  array('id' => 5, 'name' => '国际新闻', 'pid' => 1, 'level' => 1),
  array('id' => 6, 'name' => '欧洲足球', 'pid' => 4, 'level' => 2),
  array('id' => 7, 'name' => '篮球新闻', 'pid' => 2, 'level' => 1),
  array('id' => 8, 'name' => '西甲', 'pid' => 6, 'level' => 3),
  array('id' => 9, 'name' => 'NBA', 'pid' => 7, 'level' => 2)
);

函数带有子数组排列写法

function getTree($data, $pid = 0, $childrenName = "children") {
  //使用static之后,内存中就只有一份$result变量
  $result = array();
  foreach ($data as $key => $value) {
    if ($value['pid'] == $pid) {
      unset($data[$key]);
      $value[$childrenName] = getTree($data, $value['id'], $childrenName);
      $result[] = $value;
      //调用getTree进行递归
    }
  }
  return $result;
}

$res=getTree($arr);
var_dump($res);

展示一维数组的匿名函数写法

$func = function ($category, $pid = 0,$level=0) use (&$func): array {
  //使用static之后,内存中就只有一份$result变量
  static $result = array();
  foreach ($category as $key => $value) {
    if ($value['pid'] == $pid) {
      unset($category[$key]);
      //每次输出节点名时,将节点的整个数组保存到新数组
      if ($pid != 0) {
        $levelStr=str_repeat(" ",$level);
        $value['name'] = $levelStr. $value['name'];
      }
      $result[] = $value;
      //调用getTree进行递归
      $func($category, $value['id'],$level+1);
    }
  }
  return $result;
};
$res=$func($arr);
var_dump($res);
Last modification:July 28, 2022
如果觉得我的文章对你有用,请随意赞赏