在php中为每个项重启计数

时间:2013-09-17 21:02:49

标签: php arrays variables loops count

我需要代码重新开始每个$ item的计数

我的代码是:

 $count = 0;
 $folders = @scandir('Users/');  
 foreach($folders as $item){
   if (preg_match("/.*\.php$/",$item)) continue;
   echo $item;
   if (is_dir("Users/$item")){
     $target_folders = @scandir("Users/$item/uploaded/");
     foreach($target_folders as $target_item){
       if ((!preg_match("/^[.]/",$item)) ||(!is_dir("Users/$item/uploaded/$target_item"))) $count++;
     }
   }
 }

如果可以做到这一点,将非常感谢帮助。这是我项目的最后一点。

2 个答案:

答案 0 :(得分:1)

在第一个foreach循环中将$ count变量设置为零(如u_mulder建议的那样)

$count = 0;
$folders = @scandir('Users/');

foreach($folders as $item){

      $count = 0;
      if (preg_match("/.*\.php$/",$item)) 
           continue;

      echo $item;

      if (is_dir("Users/$item")){

           $target_folders = @scandir("Users/$item/uploaded/");
           foreach($target_folders as $target_item){

                if ((!preg_match("/^[.]/",$item)) || (!is_dir("Users/$item/uploaded/$target_item")))
                     $count++;

           }
      }
 }

答案 1 :(得分:0)

试试这个:

$count_result=array();
$path = "Users";
$folders = @scandir("$path");
if ($folders) {
    foreach ($folders as $item) {
        $count = 0;
        if ((substr($item, 0, 1) == '.') || (preg_match("/\.php$/", $item)))
            continue;

        if (is_dir($path . "/" . $item)) {
            echo "$item<br>";


            $target_folders = @scandir($path . "/" . $item . "/uploaded/");
            if ($target_folders) {
                foreach ($target_folders as $target_item) {
                    if ((substr($target_item, 0, 1) == '.') || is_dir("$path/$item/uploaded/$target_item"))
                        continue;
                    $count++;

                }
            }
            $count_result[$item]=$count;

        }
    }
}

var_dump($count_result);