1

我想读取一个目录并获取每个文件的文件大小。我尝试了以下代码:

$downloads = array_slice(scandir("downloads"),2);
$size = array();
foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    echo($size); //at this point the echo works correctly
}
echo($size); //shows the filesize of the first file
echo($size[1]) //nothing happens
foreach($size as $value) {
    echo($value); //nothing happens
    echo($size); //nothing happens
}

这就是为什么我现在对数组和循环的工作感到困惑。将文件名及其相应的文件大小保存在一个数组中也会很好。

感谢您的建议。

4

3 回答 3

2

你这样做是错的。您正在覆盖 foreach 中的数组。

foreach($downloads as $value) {
    $size = filesize("downloads/".$value);
    // $size is not an array anymore, just an int
    echo($size); //at this point the echo works correctly
}

这应该是正确的:

foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

完整代码:

$downloads = array_slice(scandir("downloads"),2);
$size = array();

foreach($downloads as $value) {
    $size[] = filesize("downloads/".$value);
}

foreach($size as $value) {
    echo($value).'<br/>';
}
于 2012-09-26T13:04:40.337 回答
1

您不断地覆盖变量,这就是为什么每次执行$size都不会进行它。foreach

您应该创建一个$size数组并相应地存储所有内容:

$size = array();
foreach ( $downloads as $file ) {
    $size["downloads/".$file] = filesize("downloads/".$file);
}

foreach ( $size as $fname => $fsize) {
    echo "Size of " .$fname. " is " .$fsize. " bytes.";
}
于 2012-09-26T13:05:13.670 回答
0

当您分配值时:

foreach($downloads as $value) {
$size = filesize("downloads/".$value);
回声($大小);//此时回声正常工作
}

您需要将其添加到“大小”的特定记录中

$size[ $n ] = filesize( ... );
于 2012-09-26T13:04:50.430 回答