我有一个包含'文件夹ID'的表和该文件夹'parent_id'的父目录,默认情况下根文件夹的'parent_id = 0'
---------------------------
| folder_id | parent_id |
---------------------------
| 12 | 7
| 11 | 9
| 6 | 0
| 7 | 6
| 8 | 7
| 9 | 0
| 10 | 0
我想知道给定文件夹中有多少个孩子。
当我尝试这样的递归函数时:
public function getSubFolder($fo_id , $totalSubFolders = 0){
$q = $this->db->select('*')->from('folder')->where('parentid' , $fo_id)->get();
if($q->num_rows()> 0){
foreach ($q->result() as $folder) {
$parentid = $folder->fo_id;
$totalSubFolders++;
$this->getSubFolder($parentid , $totalSubFolders);
}
}
echo $totalSubFolders;
}
当我调用此函数'getSubFolder(6)'时,输出为2331,
我不知道为什么请帮忙
答案 0 :(得分:0)
您正在回显输出,而不是将其添加到之前的值。
public function getSubFolder($fo_id , $totalSubFolders = 0){
$q = $this->db->select('*')->from('folder')->where('parentid' , $fo_id)->get();
if($q->num_rows()> 0){
foreach ($q->result() as $folder) {
$parentid = $folder->fo_id;
$totalSubFolders++;
$totalSubFolders = $this->getSubFolder($parentid , $totalSubFolders);
}
}
return $totalSubFolders;
}
public function otherFunction() {
echo $this->getSubFolder(6);
}
答案 1 :(得分:0)
结果应该是3对吗?我的意思是,如果你通过6然后 对于6我们有7和7我们有12和8所以总子文件夹为6 - > 7,8,12 = 3对吗?
你不需要更改下面的代码检查出来..声明$ totalSubFolders为public nt将其作为私有变量,否则会产生问题检查下面的代码
$totalSubFolders = 0;
public function getSubFolder($fo_id)
{
$q = $this->db->select('*')->from('folder')->where('parentid' , $fo_id)->get();
if($q->num_rows()> 0)
{
foreach ($q->result() as $folder)
{
$parentid = $folder->fo_id;
$totalSubFolders++;
$this->getSubFolder($parentid);
}
}
}
//now call the function as
public function otherFunction()
{
$this->getSubFolder(6);
echo $totalSubFolder;
}
我的工作代码我试过..