首页 > 解决方案 > 如何在laravel中获取数组元素的文件扩展名

问题描述

我正在尝试获取数据库中图像列的文件扩展名,但出现此错误:

pathinfo() 期望参数 1 是字符串,给定数组。

这是我的控制器代码如下:

$news = DB::table('news')
       ->select('image')
       ->where('id', '=', 'user_id')
       ->get();


$file = $news;
$ext = pathinfo($file, PATHINFO_EXTENSION);
return view('pages.index',compact('ext'));

这是我的看法:

@if($ext == 'mp4' || $ext == 'mov' || $ext == 'vob' || $ext == 'mpeg' || $ext == '3gp' || $ext == 'avi' || $ext == 'wmv' || $ext == 'mov' || $ext == 'amv' || $ext == 'svi' || $ext == 'flv' || $ext == 'mkv' || $ext == 'webm' || $ext == 'gif' || $ext == 'asf')
    <video width="320" height="240" controls>
        <source src="{{URL::asset('upload/news/'.$topnews->image) }}" type="video/mp4">
        Your browser does not support the video tag.
    </video>
@else
    <img src="{{ URL::asset('upload/news/'.$topnews->image) }}" class="img-responsive" alt="" width="320" height="240">
@endif

这是我的路线:

Route::get('/', 'IndexController@index');

标签: phplaravelcontroller

解决方案


遍历您的数组并应用于数组pathinfo的每个元素:

$extensions = [];
foreach ($news as $file) {
    $extensions[$file] = pathinfo($file, PATHINFO_EXTENSION);
}

推荐阅读