Problem:
I am trying to build a recursive tree using a function and data from a MySQL. However, the results are not as expected.
PHP code:
function buildTree($root, $next = array())
{
// Sanitize input
$root = (int) $root;
// Do query
$query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' AND Parent = '{$root}'";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
// Loop results
while ($row = mysql_fetch_assoc($result))
{
$next[$row['CID']] = array (
'CID' => $row['CID'],
'Item' => $row['Item'],
'Parent' => $row['Parent'],
'Children' => buildTree($row['CID'], $next)
);
}
// Free mysql result resource
mysql_free_result($result);
// Return new array
return $next;
}
$testTree = buildTree(0);
echo "<xmp>".print_r($testTree, true)."</xmp>";
The table in the database look like this:

I would like the array to be like this:
Array
(
[1] => Array
(
[CID] => 1
[Item] => Litteratur
[Parent] => 0
[Children] => Array
(
[2] => Integration av källorna
[3] => Belysning av egna resultat
[4] => Referenser
)
)
and so forth..
)
That is to say, for each parent => produce children, then move on to next parent, etc. Thank you in advance for any advice.
You do not need recursion here. In fact, it will be very inefficent since you end up with a SELECT N+1 issue. Just order the result set by parent:
This will produce the following:
If you only want the name of each children, change, use
$tree[$row['Parent']]['Children'][] = $row['Item']; instead.