php - 递归无限分类,帮忙看看代码哪里有问题?
高洛峰
高洛峰 2017-04-10 17:20:40
[PHP讨论组]
    public $cats = array();    
        
    public function category($fid=0, $level=1, $cats) {
        $sql = "select * from article_cat where cat_fid =:id";
        try {
            $stmt = $this->db->prepare($sql);
            $stmt -> bindParam(":id", $fid, PDO::PARAM_INT);
            $stmt -> execute();
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($results as $v) {
                array_push($this->cats, array($v['cat_name'], $level));
                $this-> category($v['cat_id'], $level+1, $this->cats);
                
            }

            return $this->cats;
            
        } catch(Exception $e) {
            die($e->getMessage());
        }
    }

会正确输出所有的分类值
array(6){

[
    0
]=>array(2){
    [
        0
    ]=>string(8)"3G咨询"[
        1
    ]=>int(1)
}[
    1
]=>array(2){
    [
        0
    ]=>string(12)"系统分类"[
        1
    ]=>int(1)
}[
    2
]=>array(2){
    [
        0
    ]=>string(18)"网店帮助分类"[
        1
    ]=>int(2)
}[
    3
]=>array(2){
    [
        0
    ]=>string(12)"新手上路"[
        1
    ]=>int(3)
}[
    4
]=>array(2){
    [
        0
    ]=>string(12)"手机常识"[
        1
    ]=>int(3)
}[
    5
]=>array(2){
    [
        0
    ]=>string(12)"网店信息"[
        1
    ]=>int(2)
}

}
但是如果把代码稍加修改,把cats变量由类属性改成类方法里的一个变量参数(把public $cats = array(); 删除 ),

    public function category($fid=0, $level=1, $cats = array()) {
        $sql = "select * from article_cat where cat_fid =:id";
        try {
            $stmt = $this->db->prepare($sql);
            $stmt -> bindParam(":id", $fid, PDO::PARAM_INT);
            $stmt -> execute();
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($results as $v) {
                array_push($cats, array($v['cat_name'], $level));
                $this-> category($v['cat_id'], $level+1, $cats);
                
            }

            return $cats;
            
        } catch(Exception $e) {
            die($e->getMessage());
        }
    }

输出的数据少了,只输出了顶级分类
array(2){

[
    0
]=>array(2){
    [
        0
    ]=>string(8)"3G咨询"[
        1
    ]=>int(1)
}[
    1
]=>array(2){
    [
        0
    ]=>string(12)"系统分类"[
        1
    ]=>int(1)
}

}
为什么?无法理解,问题出在哪里?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
黄舟

array_push() 函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。
该函数等于多次调用 $array[] = $value。

注释:即使数组中有字符串键名,您添加的元素也始终是数字键。(参见例子 2)
注释:如果用 array_push() 来给数组增加一个单元,还不如用 $array[] =,因为这样没有调用函数的额外负担。
注释:如果第一个参数不是数组,array_push() 将发出一条警告。这和 $var[] 的行为不同,后者会新建一个数组。

array_push(array,value1,value2...)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号