Un RecursiveParentChildIterator - comme RecursiveDirectoryIterator
-
02-10-2019 - |
Question
Il y a des tonnes d'exemples d'utilisation du RecursiveIterator pour aplatir une structure arborescente .. mais qu'en l'utiliser pour exploser une structure d'arbre?
Y at-il une façon élégante d'utiliser, ou d'une autre bibliothèque de SPL pour construire récursivement un arbre (lire: transformer un tableau plat dans un tableau de profondeur arbitraire) étant donné une table comme ceci:
SELECT id, parent_id, name FROM my_tree
EDIT: Vous savez comment vous pouvez le faire avec des répertoires?
$it = new RecursiveDirectoryIterator("/var/www/images");
foreach(new RecursiveIteratorIterator($it) as $file) {
echo $file . PHP_EOL;
}
.. Et si vous pouviez faire quelque chose comme ceci:
$it = new RecursiveParentChildIterator($result_array);
foreach(new RecursiveIteratorIterator($it) as $group) {
echo $group->name . PHP_EOL;
// this would contain all of the children of this group, recursively
$children = $group->getChildren();
}
: FIN EDIT
La solution
Bien que pas SPL, mais vous pouvez utiliser des références (&
) construire un arbre avec PHP natif:
// untested
$nodeList = array();
$tree = array();
foreach ($result as $row) {
$nodeList[$row['id']] = array_merge($row, array('children' => array()));
}
foreach ($nodeList as $nodeId => &$node) {
if (!$node['parent_id'] || !array_key_exists($node['parent_id'], $nodeList)) {
$tree[] = &$node;
} else {
$nodeList[$node['parent_id']]['children'][] = &$node;
}
}
unset($node);
unset($nodeList);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow