Jak to zostało poruszone przez @Pawan Sharma, myślałem, że mogę dać również odpowiedź.
Wszystkie podane rozwiązania cierpią na powszechny problem - wykonują zapytania SQL dla każdego dziecka. Np. Jeśli na drugim poziomie znajduje się 100 obiektów potomnych, wówczas zostanie wykonane 100 zapytań, podczas gdy w rzeczywistości można je wykonać za pomocą zapytania za pomocą where parent_id in (<list_of_ids>)
.DB
Próbka:
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');
Oto moje rozwiązanie:
/**
* @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;
}
Z dostarczonych przykładowych danych, robi co najwyżej 5 zapytań, gdy zwanych jako getTree(null)
(dla wszystkich wpisy):
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)
Wywołany jako getTree(4)
, 3 zapytania są wykonywane:
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)
Dzięki, że pomógł mi też – Umair