【问题标题】:Laravel sorting empty inputLaravel 对空输入进行排序
【发布时间】:2015-03-20 09:35:18
【问题描述】:

我正在 Laravel 中构建图像上传,但如果一个文件为空,我的 foreach 循环中会不断出现错误。

我的上传允许多张图片[],因此如果一个字段为空,我会收到错误消息,但我希望允许用户选择是否要上传,例如 2 张或 5 张图片

$input = Input::all();

//Validation

File::exists($path) or File::makeDirectory($path);
foreach($input['images'] as $file) {

    $image = Image::make($file->getRealPath()); //getRealPath gives me an error if not all images[] fields from post data containts an image

}

那么如何从空输入中对输入图像[] 进行排序?

提前致谢,

【问题讨论】:

  • 我在我的 forach 循环中添加了这个。 if($file == ""){ 中断; } 。现在它通过跳过并再次循环来工作。这个解决方案好吗?
  • 请编辑您的问题以显示您的更改,而不是在 cmets 中发布它们。

标签: php arrays sorting laravel


【解决方案1】:

如果我理解得很好,你需要这样的东西:
if(empty($file)) { unset($file); }

或类似的东西:

if(!empty($file)){
 $image = Image::make($file->getRealPath());
}

【讨论】:

    【解决方案2】:

    在运行getRealPath之前尝试检查$file是否有非空值

    File::exists($path) or File::makeDirectory($path);
    foreach($input['images'] as $file) {
        if($file) {
          $image = Image::make($file->getRealPath());
        }
    }
    

    顺便说一句,每次迭代都会重置 $image。这真的是你想要的吗?你在乎你得到哪个 $image?

    【讨论】:

      【解决方案3】:

      您可以使用不带回调的array_filter() 来删除所有具有虚假值的元素:

      $input = array_filter($input);
      foreach($input['images'] as $file) {
          $image = Image::make($file->getRealPath());
      }
      

      【讨论】:

        【解决方案4】:

        我为解决这个问题所做的就是在我的 foreach 循环中添加 if check 并且它起作用了。但我不确定这是否是最好的解决方案?

        $input = Input::all();
        foreach($input['images'] as $file) {
        
            if($file == ""){  //If one input is empty it jumps over it, instead of trying to use getRealPath() on an empty value
                    break;
            }
        
            $image = Image::make($file->getRealPath()); 
        
        }
        

        【讨论】:

        • 第一件事:您应该更新您的问题,而不是发布答案。第二件事:有时 $file 可以为 NULL 并且永远不会进入您的条件。尝试使用上面用户已经给你的答案之一。并接受其中之一。附: empty() 函数检查空字符串、0、null、false 等。所以我更愿意尽可能多地利用它。
        • @Dianna 指出,我会这样做。题外话,你知道我如何验证 Laravel 中上传的图片总数吗?例如,至少需要 1 张图片,最多需要 5 张图片。
        • 还有更多方法可以做到这一点。一个,例如,在后端(php)中进行验证,在那里您可以检查 count($images) 5 => 是否返回错误验证。例如:return Redirect: :back()->withErrors($validation);但我建议您在此处阅读有关 laravel 验证的更多信息 -> laravel.com/docs/4.2/validation
        猜你喜欢
        • 1970-01-01
        • 2018-08-19
        • 2014-11-05
        • 2017-08-10
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 2011-01-22
        相关资源
        最近更新 更多