如何从循环中获得结果数

时间:2012-04-19 17:06:40

标签: php loops foreach

我有一个上传脚本将一些文件上传到目录。每个文件都通过一个循环运行,如果有大小或结尾的错误,甚至没有错误。如果没有错误,将上传。

if (is_array($_FILES ['image'] ['tmp_name'])) {
    foreach ( $_FILES ['image'] ['tmp_name'] as $key => $val ) {
        ...

        if (! in_array ( $fileExt, $allowedExtensions )) {
            $errors [$fileName] [] = "format not accepted";
        }...

            if ((count ( $errors1 ) == 0) && (count ( $errors ) === 0))  {
               if (move_uploaded_file ( $fileTemp, $fileDst )) {
                //...                               
            }
        }   
     }
}

我的问题是,有没有办法计算成功运行该循环的上传文件的数量?非常感谢。

2 个答案:

答案 0 :(得分:2)

您需要计算每次成功上传的内容。

如下所示:

   if (is_array($_FILES ['image'] ['tmp_name'])) {
    $Counter=0;     // initialize counter variable
        foreach ( $_FILES ['image'] ['tmp_name'] as $key => $val ) {

            $fileName = $_FILES ['image'] ['name'] [$key];
            $fileSize = $_FILES ['image'] ['size'] [$key];
            $fileTemp = $_FILES ['image'] ['tmp_name'] [$key];

            $fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
            $fileExt = strtolower ( $fileExt );

            if (empty ( $fileName ))
            continue;

            if (! in_array ( $fileExt, $allowedExtensions )) {
                $errors [$fileName] [] = "format not accepted";
            }...

                if ((count ( $errors1 ) == 0) && (count ( $errors ) === 0))  {
                   if (move_uploaded_file ( $fileTemp, $fileDst )) {
                    //...           
                   $Counter++;       // increment if successful upload
                }
            }   
         }
    }

echo $Counter;  //it will give total count of successfully uploaded files

答案 1 :(得分:1)

只需使用计数器变量。我知道你在move_uploaded_file返回true时成功上传了一个文件,对吗?

$counter = 0;
//... your code
if ((count ( $errors1 ) == 0) && (count ( $errors ) === 0))  {
    if (move_uploaded_file ( $fileTemp, $fileDst )) {
        $counter++;
        //... some other code
    }
}

因此,当您离开foreach循环时,$counter将具有预期值。