dpjpo746884
2016-06-03 14:49
浏览 268
已采纳

Php / Laravel - 从请求数组中获取最后一个元素

I am trying to get the last element of the request array in foreach loop that would look something like this:

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"
]

But I can't use the end() function because then I get:

Only variables should be passed by reference

This is how foreach function looks like:

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]);
        }

图片转代码服务由CSDN问答提供 功能建议

我试图在foreach循环中获取请求数组的最后一个元素,如下所示:

 数组: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){
 
 //为文章创建一个新目录并移动所有 上传的文件
 $ filePathArr = explode('/',$ file); 
 $ lastItem = array_pop($ filePathArr); 
 array_push($ filePathArr,$ article-> id,$ lastItem); \  n $ 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]); 
} 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douya5194 2016-06-03 14:56
    已采纳

    Why call $request->get('uploadedItems') multiple times? Call it once and assign it to a variable before the loop or:

    foreach ($files = $request->get('uploadedItems') as $file) {
    
        if(end($files) == $file){
            dd($file);
        }
    
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题