The output of the function looks good but I’m getting extra [0] => Array ( [1] => 1 ) from nowhere everytime. The id’s are starting from 1 in my db table. Where is 0 appearing from?!
Array ( [1] => Array ( [name] => Sual [parent] => 0 ) **[0] => Array ( [1] => 1 )** ...
Here is the function
<?php
function treeGen($menu, $utype) {
global $db;
$tree = array();
$stmt = $db->prepare("select id, parent, name FROM navigation WHERE menu=? AND user_type=?") or die($db->error);
$stmt->bind_param("ii", $menu, $utype) or die($stmt->error);
$stmt->execute() or die($stmt->error);
$stmt->store_result();
$meta = $stmt->result_metadata();
$stmt->bind_result($id, $parent, $name);
while ($stmt->fetch()) {
$tree[$id] = array(
'name' => $name,
'parent' => $parent
);
if (!array_key_exists($parent,$tree)) {
$tree[$parent][$id] = $id;
}
}
$stmt->close();
print_r($tree);
}
?>
I imagine the problem comes when you encounter a top-level row from the table (a row without a parent). When you process one of these rows,
$parentis null and this conditional fires:Here
$parentis null, which is interpreted as 0, which isn’t a key that exists in$parent(at least, not the first time you encounter a row like this), so this results in$tree[0]being created. In your case, the first row whereparentis null is the row withid = 1, hence$tree[0]isarray(1 => 1).Change the above conditional to the following:
or if your DB wrapper does not use the PHP
nulltype to represent SQLNULLvalues, use something like this: