Domanda

Ci sono tonnellate di esempi di utilizzo del RecursiveIterator per appiattire una struttura ad albero .. ma che dire di usarlo per esplodere una struttura ad albero?

C'è un modo elegante per utilizzare questo, o qualche altra libreria SPL a ricorsivamente costruire un albero (leggi: trasformare una matrice piatta nella gamma di profondità arbitraria) dato una tabella come questa:

SELECT id, parent_id, name FROM my_tree

Modifica Sapete come si può fare questo con le directory?

$it = new RecursiveDirectoryIterator("/var/www/images");
foreach(new RecursiveIteratorIterator($it) as $file) {
    echo $file . PHP_EOL;
}

.. E se fosse possibile fare qualcosa di simile:

$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();
}

: END EDIT

È stato utile?

Soluzione

Anche se non SPL, ma è possibile utilizzare i riferimenti (&) costruire un albero con PHP nativa:

// 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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top