为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
ibeautiful 2023-10-22 20:57:43
我需要从目录中找到最小的文件大小。使用 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 arrayforeach ($files as $key => $file){    $files[$key] = ['file' => $file, 'size' => Storage::size($file)]; }$min = collect($files)->min('size'); // 1000000// find file by size...
查看完整描述

2 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

我认为您可以使用回调根据文件大小对文件进行排序。也许是这样的东西,sortBy


//after Arr::where

$fileWithSmallestSize = collect($files)->sortBy(function($file){

    return Storage::size($file);

})->first();

另一种选择是减少收集。


//after Arr::where

$fileWithSmallestSize = collect($files)->reduce(function($smallestFile, $file){

    return ( Storage::size($file) < Storage::size($smallestFile) )? $file : $smallestFile;

}, $files[0]);


查看完整回答
反对 回复 2023-10-22
?
慕容森

TA贡献1853条经验 获得超18个赞

循环文件时保持最小:


$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


$minSize = PHP_INT_MAX;

$minFile = null;

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

{

    $size = Storage::size($file);

    if ($size < $minSize) {

      $minSize = $size;

      $minFile = $file;

    }

    $files[$key] = ['file' => $file, 'size' => $size]; 

    

}


// $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



查看完整回答
反对 回复 2023-10-22
  • 2 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信