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)
}
}
为什么?无法理解,问题出在哪里?
先解决下楼主的的问题
楼主的第二段代码核心在于数组变量的引用,由于楼主的代码
输出结果
我的解决方式
代码
数据库
输出结果