@Pawan Sharma 提出了这个问题,我想我也可以给出一些答案。
所有给定的解决方案都存在共同问题——它们对每个孩子执行 SQL 查询。例如,如果第 2 级有 100 个孩子,那么将完成 100 个查询,而实际上可以在 single 查询中使用where parent_id in (<list_of_ids>) 完成。
示例数据库:
create table category (
id int auto_increment primary key,
parent_id int default null,
title tinytext,
foreign key (parent_id) references category (id)
) engine = InnoDB;
insert into category (id, parent_id, title) values
(1, null, '1'),
(2, null, '2'),
(3, null, '3'),
(4, 1 , '1.1'),
(5, 1 , '1.2'),
(6, 1 , '1.3'),
(7, 4 , '1.1.1'),
(8, 4 , '1.1.2'),
(9, 7 , '1.1.1.1');
这是我的解决方案:
/**
* @param null|int|array $parentID
*/
function getTree($parentID) {
$sql = "select id, parent_id, title from category where ";
if ( is_null($parentID) ) {
$sql .= "parent_id is null";
}
elseif ( is_array($parentID) ) {
$parentID = implode(',', $parentID);
$sql .= "parent_id in ({$parentID})";
}
else {
$sql .= "parent_id = {$parentID}";
}
$tree = array();
$idList = array();
$res = mysql_query($sql);
while ( $row = mysql_fetch_assoc($res) ) {
$row['children'] = array();
$tree[$row['id']] = $row;
$idList[] = $row['id'];
}
mysql_free_result($res);
if ( $idList ) {
$children = getTree($idList);
foreach ( $children as $child ) {
$tree[$child['parent_id']]['children'][] = $child;
}
}
return $tree;
}
使用提供的示例数据,当调用 getTree(null)(所有条目)时,它最多执行 5 次查询:
select id, parent_id, title from category where parent_id is null
select id, parent_id, title from category where parent_id in (1,2,3)
select id, parent_id, title from category where parent_id in (4,5,6)
select id, parent_id, title from category where parent_id in (7,8)
select id, parent_id, title from category where parent_id in (9)
以getTree(4) 调用时,执行3 次查询:
select id, parent_id, title from category where parent_id = 4
select id, parent_id, title from category where parent_id in (7,8)
select id, parent_id, title from category where parent_id in (9)