-2
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?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
GOsha
  • 689
  • 5
  • 13

4 Answers4

4

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
  • 31,886
  • 13
  • 87
  • 111
2

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.

Community
  • 1
  • 1
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

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
  • 249,484
  • 69
  • 436
  • 539
0

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

powtac
  • 40,542
  • 28
  • 115
  • 170