php递归无限级分类

  • 内容
  • 评论
  • 相关

本来这些东西在电脑面前写起来是挺容易的,但是在面试的时候,口头上却说不出来。不说了,直接上代码吧,当是巩固,祝自己早日找到工作。

<?php 

$arr = [
	['id' => 1, 'pid' => 0, 'name' => '广东省'],
	['id' => 2, 'pid' => 0, 'name' => '北京市'],
	['id' => 3, 'pid' => 1, 'name' => '广州市'],
	['id' => 4, 'pid' => 2, 'name' => '朝阳区'],
	['id' => 5, 'pid' => 2, 'name' => '通州区'],
	['id' => 6, 'pid' => 4, 'name' => '望京'],
	['id' => 7, 'pid' => 4, 'name' => '酒仙桥'],
	['id' => 8, 'pid' => 3, 'name' => '番禺区'],
	['id' => 9, 'pid' => 1, 'name' => '江门市'],	
];

function categoryTree($arr, $pid = 0, $level = 0){
	static $list = [];
	foreach ($arr as $key => $value) {
		if ($value['pid'] == $pid) {
			$value['level'] = $level;
			$list[] = $value;
			unset($arr[$key]);
			categoryTree($arr, $value['id'], $level+1);
		}
	}
	return $list;
}

$res = categoryTree($arr);

foreach ($res as $key => $value) {
	echo str_repeat('--', $value['level']).$value['name'].'<br>';
}

结果如下: