views:

63

answers:

4
function build_path($cid)
{
    static $fr=array();
    $DB = new MySQLTable;
    $DB->TblName = 'shop_categories';
    $where['cat_id']['='] = $cid;
    $res = $DB->Select('cat_id,cat_name,cat_parent', $where);
    if($res !== false)
    {
        $pid = mysql_fetch_array($res);
        if($pid['cat_parent'] !== "0")
        {
           $fr[] = $pid['cat_id'];
           build_path($pid['cat_parent']);
        } else {
            $fr[] = $cid;
            $fr = array_reverse($fr);
            print_r($fr);
            return $fr;
        }
    }
}

print_r(build_path(100));

Why is working print_r in function, but second print_r returns NULL?

+4  A: 

Normally, for a recursive function to work, you need to return something when calling itself.

Try this in your first nested if block:

return build_path($pid['cat_parent']);
Mike B
A: 

Recursive functions must not use static to pass the data through invokes - use the arguments instead.

And why do you need this line:

if($res !== false)

??

zerkms
this class returns resource id if query is ok, and false if i have mysql error
GOsha
@GOsha: if you write proper queries - you would never get mysql query error
zerkms
if db server is down, or if smth getting wrong
GOsha
If server is down it is better to throw an exception.
zerkms
+2  A: 

FYI, You wouldn't need to write a recursive function or execute N queries for N levels of hierarchy if you used one of the various methods for storing hierarchical data in a database.

Bill Karwin
A: 

Instead of build_path($pid['cat_parent']); in line 14 use return build_path($pid['cat_parent']);.

powtac