由於這已經由@Pawan Sharma提出,我認爲我也可以給出一些答案。
所有給定的解決方案都有一個共同的問題 - 他們爲每個孩子執行SQL查詢。例如,如果第二級中有100個孩子,則將完成100個查詢,而實際上可以通過使用where parent_id in (<list_of_ids>)
在單個查詢中完成。
樣品DB:
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;
}
利用所提供的樣本數據,它最多5個查詢,當作爲getTree(null)
呼籲(所有條目):
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)
感謝它也幫助了我 – Umair 2015-01-22 07:35:59