php - Build a multidimensional array using recursive function -
problem:
i trying build recursive tree using function , data mysql. however, results not expected.
php code:
function buildtree($root, $next = array()) { // sanitize input $root = (int) $root; // query $query = "select cid, item, parent betyg_category status = '1' , 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 database this:
i array this:
array ( [1] => array ( [cid] => 1 [item] => litteratur [parent] => 0 [children] => array ( [2] => integration av källorna [3] => belysning av egna resultat [4] => referenser ) ) , forth.. )
that say, each parent => produce children, move on next parent, etc. thank in advance advice.
you not need recursion here. in fact, inefficent since end select n+1 issue. order result set parent:
$query = "select cid, item, parent betyg_category status = '1' order parent"; $result = mysql_query($query); $tree = array(); while($row = mysql_fetch_assoc($result)) { if($row['parent'] == 0) { $row['children'] = array(); $tree[$row['cid']] = $row; } else { $tree[$row['parent']]['children'][] = $row; } }
this produce following:
array ( [1] => array ( [cid] => 1 [item] => litteratur [parent] => 0 [children] => array ( [0] => array ( [cid] => 2 [item] => integration av källorna [parent] => 1 ) [1] => array ( [cid] => 3 [item] => belysning [parent] => 1 ) [2] => array ( [cid] => 4 [item] => referenser [parent] => 1 ) ) ) [5] => array ( [cid] => 5 [item] => validitet [parent] => 0 [children] => array ( [0] => array ( [cid] => 6 [item] => huvudsyfte [parent] => 5 ) ) ) )
if want name of each children, change, use $tree[$row['parent']]['children'][] = $row['item']
; instead.
Comments
Post a Comment