Php 如何在laravel中获取数组元素的文件扩展名
我试图获取数据库中图像列的文件扩展名,但出现以下错误: pathinfo要求参数1为字符串,数组给定 以下是我的控制器代码:Php 如何在laravel中获取数组元素的文件扩展名,php,laravel,controller,Php,Laravel,Controller,我试图获取数据库中图像列的文件扩展名,但出现以下错误: pathinfo要求参数1为字符串,数组给定 以下是我的控制器代码: $news = DB::table('news') ->select('image') ->where('id', '=', 'user_id') ->get(); $file = $news; $ext = pathinfo($file, PATHINFO_EXTENSION); return view('
$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
迭代数组并将pathinfo应用于数组的每个元素:
$extensions = [];
foreach ($news as $file) {
$extensions[$file] = pathinfo($file, PATHINFO_EXTENSION);
}
从查询返回第一个对象,并从模型的image属性获取扩展名 $topnews=DB::表'news' ->选择“图像” ->其中'id','=',$user\u id ->第一,; $ext=pathinfo$topnews->image,pathinfo\u扩展名; 返回视图'pages.index',压缩'ext',热门新闻'; 希望这有帮助 我还希望您不在视图中的foreach循环中: 交叉手指Laravel提供了一个值函数,可直接从查询中接收值 将您的查询更改为
$news = DB::table('news')
->select('image')
->where('id', '=', 'user_id')
->value('image');
您也可以省略select,因为该值已经执行了该操作
$news = DB::table('news')
->where('id', '=', 'user_id')
->value('image');
如果您的Laravel版本不支持值,请先使用
所以在数组上迭代,不是吗?我得到了这个错误:致命错误:调用ArrayId上的成员函数映射你在得到后编写映射吗?是的,我使用了你发送的确切代码。错误表明我无法在arraydoesn上使用map没有任何意义,请尝试更新的代码,编辑问题并发布您的视图编辑问题并添加路由和控制器方法和视图:没有代码我们无法帮助您我的视图中有未定义的变量扩展,可能是因为它不是全局的。那么我如何才能像其他变量一样将$extension变量的新值加载到我的视图中呢?谢谢你的回答,但我尝试打印变量$extensions,但没有打印。我遇到的问题似乎是:$ext=pathinfo$file,pathinfo\u扩展名;$文件是一个数组,并给出了一个错误
$news = DB::table('news')
->where('id', '=', 'user_id')
->value('image');
$news = DB::table('news')
->select('image')
->where('id', '=', 'user_id')
->first()->image;