I have a website with articles and sections, each sections can have a parent section, as much as they like for example:
subject 1
-subject 2
--subject 3
-subject 4
--subject 5
--subject 6
---subject 7
subject 8
subject 9
etc..
Now, i want to fetch them recursively, what is the most efficient way to do it via php and mysql?
Tnx in advanced.
A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the recursion. The iterative fullselect contains a direct reference to itself in the FROM clause.
Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Naming the result and referencing it within other queries.
First, execute the anchor member to form the base result set (R0), use this result for the next iteration. Second, execute the recursive member with the input result set from the previous iteration (Ri-1) and return a sub-result set (Ri) until the termination condition is met.
If the tree isn't too large, you can simply build the tree in PHP using some clever references.
$nodeList = array();
$tree = array();
$query = mysql_query("SELECT category_id, name, parent FROM categories ORDER BY parent");
while($row = mysql_fetch_assoc($query)){
$nodeList[$row['category_id']] = array_merge($row, array('children' => array()));
}
mysql_free_result($query);
foreach ($nodeList as $nodeId => &$node) {
if (!$node['parent'] || !array_key_exists($node['parent'], $nodeList)) {
$tree[] = &$node;
} else {
$nodeList[$node['parent']]['children'][] = &$node;
}
}
unset($node);
unset($nodeList);
This will give you the tree structure in $tree
with the children in the respective children
-slot.
We've done this with fairly large trees ( >> 1000 items) and it's very stable and a lot faster than doing recursive queries in MySQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With