我有一个包含'文件夹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;
}
当我称此函数为" getubFolder(6)"时,输出为2331,
我不知道为什么请帮助
嗨,结果应该是3对吗?我的意思是,如果您通过6 对于6,我们有7个,对于7,我们有12个和8个,因此6-> 7、8、12 = 3对?
您无需更改以下代码查看。
$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;
}
我尝试过的工作代码..
您正在回荡您的输出,而不是将其添加到上一个值中。
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);
}