Mammouth du PHP |
1885 Messages
12 févr. 2005, 23:25
Le moyen le plus optimisé de le faire est l'utilisation des "Nested Sets". Voici des explications très techniques sur leurs utilisations:
http://www.dbazine.com/tropashko4.shtml
Cependant, si tu peux te permettre un appel récursif générant une requête SQL par résursion, tu peux créer une fonction qui se charge d'aller chercher tous les enfants portant l'ID du noeud courant et ainsi parcourir tous ceux-ci.
Exemple
Code : Tout sélectionner
uid pid name
1 0 Section 1
2 0 Section 2
3 0 Section 3
4 1 Section 1.1
5 1 Section 1.2
6 1 Section 1.3
7 4 Section 1.1.1
8 4 Section 1.1.2
9 2 Section 2.1
10 2 Section 2.2
Fonction et requête non-optimisée
Ne comprend pas la gestion de l'arborescence avec espaces car je suis un peu pressé.
<?php
function node($pid=0) {
$sql = 'SELECT uid, pid, name
FROM nodes
WHERE pid='.intval($pid);
$res = mysql_query($sql) or die(mysql_error());
if (FALSE != ($row = mysql_fetch_array($res))) {
do {
echo $row['name'] . '<br />';
node($row['uid']);
} while (FALSE != ($row = mysql_fetch_array($res)));
}
}
?>
Arborescence résultat
Code : Tout sélectionner
Section 1 (1)
Section 1.1 (4)
Section 1.1.1 (7)
Section 1.1.2 (8)
Section 1.2 (5)
Section 1.3 (6)
Section 2 (2)
Section 2.1 (9)
Section 2.2 (10)
Section 3 (3)

La programmation est l'expression de la poésie d'un programmeur
Génération PHP