heron
heron

Reputation: 3661

Function outputs array 0 elements from nowhere

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

?>

Upvotes: 1

Views: 90

Answers (2)

user1006565
user1006565

Reputation:

something is going wrong in

if (!array_key_exists($parent,$tree)) {
        $tree[$parent][$id] = $id;

i think. try commenting this code and then print the array $tree

Upvotes: 0

Hammerite
Hammerite

Reputation: 22340

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, $parent is null and this conditional fires:

if (!array_key_exists($parent,$tree)) {
    $tree[$parent][$id] = $id;
}

Here $parent is 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 where parent is null is the row with id = 1, hence $tree[0] is array(1 => 1).

Change the above conditional to the following:

if (!array_key_exists($parent,$tree) and !is_null($parent)) {

or if your DB wrapper does not use the PHP null type to represent SQL NULL values, use something like this:

if (!array_key_exists($parent,$tree) and $parent != 0) {

Upvotes: 1

Related Questions