猿问

在带有 Laravel 的目录中查找最小文件大小?

我需要从目录中找到最小的文件大小。使用 Laravel并尽可能减少代码的最佳方法是什么?


我正在使用这段代码,但我相信有一种更好、更有效的方法。


$files = Storage::files("videos");


$files = Arr::where($files, function ($value, $key) {

    return Str::contains($value, 'string..') && Str::endsWith($value ,'.mp4');

}); // keep only certain files from videos directory in the files array


foreach ($files as $key => $file)

{

    $files[$key] = ['file' => $file, 'size' => Storage::size($file)]; 

}


$min = collect($files)->min('size'); // 1000000


// find file by size...


ibeautiful
浏览 124回答 2
2回答

PIPIONE

我认为您可以使用回调根据文件大小对文件进行排序。也许是这样的东西,sortBy//after Arr::where$fileWithSmallestSize = collect($files)->sortBy(function($file){&nbsp; &nbsp; return Storage::size($file);})->first();另一种选择是减少收集。//after Arr::where$fileWithSmallestSize = collect($files)->reduce(function($smallestFile, $file){&nbsp; &nbsp; return ( Storage::size($file) < Storage::size($smallestFile) )? $file : $smallestFile;}, $files[0]);

慕容森

循环文件时保持最小:$files = Storage::files("videos");$files = Arr::where($files, function ($value, $key) {&nbsp; &nbsp; return Str::contains($value, 'string..') && Str::endsWith($value ,'.mp4');}); // keep only certain files from videos directory in the files array$minSize = PHP_INT_MAX;$minFile = null;foreach ($files as $key => $file){&nbsp; &nbsp; $size = Storage::size($file);&nbsp; &nbsp; if ($size < $minSize) {&nbsp; &nbsp; &nbsp; $minSize = $size;&nbsp; &nbsp; &nbsp; $minFile = $file;&nbsp; &nbsp; }&nbsp; &nbsp; $files[$key] = ['file' => $file, 'size' => $size];&nbsp;&nbsp; &nbsp;&nbsp;}// $minSize is the smallest size in the directory and $minFile is the file with the smallest size// $minFile will be `null` if there are no files in the initial array, you should add a check for this possibility
随时随地看视频慕课网APP
我要回答