开发者

how to return static variable PHP

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?


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']);


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.

  • What is the most efficient/elegant way to parse a flat table into a tree?
  • Retrieving data with a hierarchical structure in MySQL
  • Models for Hierarchical Data with SQL and PHP.


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)

??


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜