我试图在foreach循环中获取请求数组的最后一个元素,如下所示:
array:5 [▼
0 => "files/uploads/articles/bear_PNG1183.png"
1 => "files/uploads/articles/bear_PNG1189.png"
2 => "files/uploads/articles/bear_PNG1188.png"
3 => "files/uploads/articles/bear_PNG1182 (1).png"
4 => "files/uploads/articles/bear_PNG1190.png"
]
但是我不能使用end()
函数,因为我得到了:
只应通过引用传递变量
这是foreach函数的样子:
foreach ($request->get('uploadedItems') as $file) {
//make a new directory for the article and move all the uploaded files to it
$filePathArr = explode('/', $file);
$lastItem = array_pop($filePathArr);
array_push($filePathArr, $article->id, $lastItem);
$newPath = implode('/', $filePathArr);
$articleDirectory = $this->destinationPath.'/'.$article->id;
if(!File::exists($articleDirectory))
File::makeDirectory($articleDirectory, 0755, true);
File::move(public_path($file), public_path($newPath));
if(end($request->get('uploadedItems')) == $file){
dd($file);
}
Media::create(['path' => $newPath, 'article_id' => $article->id]);
}
答案 0 :(得分:3)
为什么多次致电$request->get('uploadedItems')
?调用一次并在循环之前将其分配给变量或:
foreach ($files = $request->get('uploadedItems') as $file) {
if(end($files) == $file){
dd($file);
}
}