-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
  • 499,602
  • 82
  • 638
  • 795
GOsha
  • 709
  • 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,390
  • 13
  • 83
  • 110
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
  • 499,602
  • 82
  • 638
  • 795
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
  • 240,587
  • 65
  • 429
  • 525
0

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

powtac
  • 39,317
  • 26
  • 112
  • 166