PHP无限级树形结构算法(递归和引用)
测试数组
$array = [ ['id' => 1, 'pid' => 0, 'name' => '这是主类'], ['id' => 2, 'pid' => 0, 'name' => '这是主类'], ['id' => 3, 'pid' => 1, 'name' => '父级为1子类'], ['id' => 4, 'pid' => 2, 'name' => '父级为2子类'], ['id' => 5, 'pid' => 3, 'name' => '父级为3子类'], ];
一、递归算法
function tree($array, $pid) { $tree = array(); foreach ($array as $key => $value) { if ($value['pid'] == $pid) { $value['child'] = tree($array, $value['id']); if (!$value['child']) { unset($value['child']); } $tree[] = $value; } } return $tree; } echo "<pre>" . print_r(tree($array, 1), 1) . "</pre>";
二、数组引用
function generateTree($rows, $id = 'id', $pid = 'pid') { $items = array(); foreach ($rows as $row) { $items[$row[$id]] = $row; } foreach ($items as $item) { $items[$item[$pid]]['son'][$item[$id]] = &$items[$item[$id]]; } return isset($items[0]['son']) ? $items[0]['son'] : array(); } echo "<pre>" . print_r(generateTree($array), 1) . "</pre>";