2013-01-20 50 views
0

我有一個php代碼,將顯示我有一個文件夾中的文件數量。從多個文件夾和回聲總數php計數文件

代碼:這將呼應這樣我的網頁上, 「共有119條是」

$directory = "../health/"; 
if (glob($directory . "*.php") != false) /* change php to the file you require either html php jpg png. */ { 
    $filecount = count(glob($directory . "*.php")); /* change php to the file you require either html php jpg png. */ 
    echo "<p>There are a total of"; 
    echo " $filecount "; 
    echo "Articles</p>"; 
} else { 
    echo 0; 
} 

問:

我想從計數文件27個或更多文件夾並回顯文件總數。

有沒有去,我可以添加文件夾列表打開,如:

$directory = "../health/","../food/","../sport/"; 

那麼它會計算所有的文件和顯示總

「共有394條是」

感謝

+2

究竟阻止你算來自這三個目錄中的文件? – hakre

回答

3

是,您可以:

glob('../{health,food,sport}/*.php', GLOB_BRACE); 
+0

這應該放在代碼的哪裏?我嘗試了各種各樣,但它似乎只顯示健康文件夾中的總數。另外兩個傢伙有工作解決方案,但他們說你的方法也更好,也可以使用方法。 [link] http://test.whatswered.com/health/what-c​​an-a-first-aider-do.php – mally

+0

'$ filecount = count(glob('../ {health, food,sport}/*。php',GLOB_BRACE));'將從3個目錄中返回* .php文件的數量。 – clover

+0

謝謝我之前嘗試過,但我現在一定做了錯誤的工作,非常感謝您的幫助。 – mally

0

您可以使用執行opendir命令解釋在這裏: http://www.php.net/manual/en/function.opendir.php

與以前的鏈接上顯示的合併例如:

<?php 
$dir = "/etc/php5/"; 

// Open a known directory, and proceed to read its contents 
if (is_dir($dir)) { 
    if ($dh = opendir($dir)) { 
     while (($file = readdir($dh)) !== false) { 
      echo "filename: $file : filetype: " . filetype($dir . $file) . "\n"; 
     } 
     closedir($dh); 
    } 
} 
?> 

基本上打開文件夾,你先通過,並在循環計數每辛格運河項目是不是一個文件夾。

編輯: 似乎有人給出了比這更簡單的解決方案。

1

毫無疑問,這是比clover的回答效率較低:

$count = 0; 
$dirs = array("../health/","../food/","../sport/"); 
foreach($dirs as $dir){ 
    if($files = glob($dir."*.php")){ 
     $count += count($files); 
    } 
} 

echo "There are a total of $count Articles"; 
1

一個簡單的解決辦法是隻使用一個陣列和一個循環。這是你自己想出來的。

$directories = array('../health/', '../food/', '../sport/'); 
$count = 0; 
foreach ($directories as $dir) { 
    $files = glob("{$dir}*.php") ?: array(); 
    $count += count($files); 
} 
echo "<p>There are a total of {$count} articles</p>"; 

但是,@ clover的答案是更好的。

1

像往常一樣,分割問題通常要好得多。例如:

  • 獲取文件(請參閱glob)。
  • 計算glob結果的文件(編寫一個函數,用於處理FALSEArray兩個案例。)。
  • 執行輸出(不要在其他代碼中執行輸出,在最後執行,使用變量(因爲您已經這樣做,只是將輸出分開))。

一些示例代碼:

/** 
* @param array|FALSE $mixed 
* @return int 
* @throws InvalidArgumentException 
*/ 
function array_count($mixed) { 

    if (false === $mixed) { 
     return 0; 
    } 
    if (!is_array($mixed)) { 
     throw new InvalidArgumentException('Parameter must be FALSE or an array.'); 
    } 

    return count($mixed); 
} 

$directories = array("health", "food", "string"); 
$pattern  = sprintf('../{%s}/*.php', implode(',', $directories)); 
$files  = glob($pattern, GLOB_BRACE); 
$filecount = array_count($files); 

echo "<p>There are a total of ", $filecount, " Article(s)</p>";