2015-10-22 72 views
0

我已經查看了系統中已有的問題,但無法找到我的問題的答案。我想在php遞歸函數中嘗試一個計數器,它會查找並刪除空文件夾。我粘貼下面的方式來將非空容器回顯爲「 - 」並清空爲「|」。它畢竟看起來不錯,但如果有很多需要清除的東西,它會在屏幕上變成亂碼。相反,我希望看到已刪除的文件夾數量。以下是使用StackOverflow編譯的代碼。任何幫助嗎?計數器在PHP遞歸函數

function RemoveEmptySubFolders($path) { 
    echo "–"; 
    $empty = true; 
    foreach (glob ($path . DIRECTORY_SEPARATOR . "*") as $file) { 
     if (is_dir ($file)) { 
      if (! RemoveEmptySubFolders ($file)) 
       $empty = false; 
     } else { 
      $empty = false; 
     } 
    } 
    if ($empty) { 
     if (is_dir ($path)) { 
     // echo "Removing $path...<br>"; 
     rmdir ($path); 
     echo "|"; 
     } 
    } 
    return $empty; 
} 
+1

你可以在你的函數中使用引用:function RemoveEmptySubFolders($ path,&$ cnt):http://php.net/manual/en/language.references.pass.php – Steven

+0

你想查看總數所有刪除vs空的總數還是隻有實際遞歸的總和? – inetphantom

+0

所以請接受解決您的問題的答案。看看[tour](stackoverflow.com/tour)使用SO – inetphantom

回答

4

只是傳遞變量作爲參考:

function recursive($path, &$directories, &$removed) { 
    echo "-"; 
    $directories ++; 
    $empty = true; 
    foreach (glob ($path . DIRECTORY_SEPARATOR . "*") as $file) { 
     if (is_dir ($file)) { 
      if (! recursive ($file, $directories, $removed)) 
       $empty = false; 
     } else { 
      $empty = false; 
     } 
    } 
    if ($empty) { 
     if (is_dir ($path)) { 
      $removed++; 
      echo "|"; 
     } 
    } 
    return $empty; 
} 

$path = "c:\exampledir"; 
$directories = 0; 
$removed = 0; 
recursive($path, $directories, $removed); 
echo("<br>$directories, $removed"); 

你也可以使用全局變量,但這是非常難看,而且每次使用全局變量othen比標準的,一隻小貓死。

+0

投票支持小貓! – inetphantom

+0

Thanx男人,它現在的作品!我的錯誤是未能將函數本身傳遞給'if(!recursive($ file,$ directories,$ removed))'中增加的變量。 – KirKu

+0

現在的啓發我已經添加&$ dash_count爲樂趣:$ dash_count ++;如果($ dash_count> 70){echo「 -
」; $ dash_count = 0; } else echo「 - 」; – KirKu

0

面向對象變種:

把一切都放在一個類並添加實例屬性$checked$deleted,然後用自制程序或(討厭的代碼),只需用+= 1$var ++遞增它們。