这个递归函数有什么问题?

时间:2012-01-24 07:34:53

标签: php recursion

这是我的递归函数:

function get_descendants($category_id)
{
    global $descendants;

    $categories = get_ancestors($category_id);
echo "get_ancestors($category_id);<br>";

//  print_r($categories);exit;

    if (!is_array($categories))
        return;

    foreach ($categories as $category)
    {
        $descendants[] = $category['id'];

        // Look for other leafs
        get_descendants($category['id']);
    }

    return $descendants;
}

function get_ancestors($parent_id)
{
    global $db, $locale;

    $result = $db->query("
            SELECT ...
                AND parent_id = $parent_id
    ");

    $categories = $result->fetch_all(MYSQLI_ASSOC);

    if ($result->num_rows > 0)
    {
        foreach ($categories as $category)
            $data[] = $category;

        return $data;
    }
}

问题是两次同一个电话。所以这是运行代码的结果:

get_ancestors(8);
get_ancestors(1);
get_ancestors(2);
get_ancestors(4);
get_ancestors(5);
get_ancestors(3);
get_ancestors(6);
get_ancestors(8);
get_ancestors(1);
get_ancestors(2);
get_ancestors(4);
get_ancestors(5);
get_ancestors(3);
get_ancestors(6);

我应该只看到:

get_ancestors(8);
get_ancestors(1);
get_ancestors(2);
get_ancestors(4);
get_ancestors(5);
get_ancestors(3);
get_ancestors(6);

怎么了?

感谢。

1 个答案:

答案 0 :(得分:2)

问题是您希望$descendants成为global

您正在所有递归调用中共享一个变量。对于你用来纠正的逻辑,它确实需要是本地的。

而不是global $descendants;$descendants = array();

相关问题