Come questo è stato sollevato da @Pawan Sharma, ho pensato che potrei dare qualche risposta pure.
Tutte le soluzioni fornite soffrono di un problema comune: eseguono query SQL per ogni bambino. Ad esempio, se ci sono 100 bambini al 2 ° livello, verranno effettuate 100 query, mentre può essere effettivamente eseguita nella query singola utilizzando where parent_id in (<list_of_ids>)
.
Esempio 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');
Ecco la mia soluzione:
/**
* @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;
}
Con i dati di esempio forniti, lo fa al massimo 5 query, quando viene chiamato come getTree(null)
(per tutti voci):
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)
Quando viene chiamato come getTree(4)
, 3 query vengono eseguiti:
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)
Grazie anche a me – Umair