简体   繁体   English

如何在 Laravel 会话数组中添加项目

[英]How to add items in Laravel session array

I'm using Laravel 4.2.我正在使用 Laravel 4.2。 I have a method for storing files and I'm trying to push items in session array.我有一种存储文件的方法,我正在尝试将项目推送到会话数组中。 Every time user clicks on a button, I want to save these file names in session array with a name and later I should get them.每次用户单击按钮时,我都想将这些文件名保存在会话数组中并命名,稍后我应该获取它们。

I'm trying with the following code:我正在尝试使用以下代码:

 $name = Input::get('name'); $input = Input::all(); foreach ($input[$name] as $key => $corporate) { $file_name = $key.'_'.$current_time . '_' . $corporate->getClientOriginalName(); //code for uploading files if(Session::has($name)) { Session::push($name.".".$key, $file_name); //I want to add new items in this array } else { Session::put($name, $file_name); //for first image } }

As I read from laravel docs:正如我从 laravel 文档中读到的那样:

Push A Value Onto An Array Session Value将值推入数组会话值

Session::push('user.teams', 'developers'); Session::push('user.teams', 'developers');

);` );`

But it doesn't add new items to array, it overwrites it.但它不会向数组添加新项目,而是会覆盖它。

After first image upload in session array I have:在会话数组中上传第一张图像后,我有:

 ["director_front_passport[]"]=> array(1) { [1]=> array(1) { [0]=> string(54) "0_1472669237_12894473_678457885627912_1258115018_o.jpg" } }

After uploading second image, session is:上传第二张图片后,会话是:

 ["director_front_passport[]"]=> array(1) { [2]=> array(1) { [0]=> string(33) "0_1472669255_animated_loading.gif" } }

What is the proper way to push items in session array with definite name, I mean I should get these items later using: Session::get('name') for example.在会话数组中推送具有明确名称的项目的正确方法是什么,我的意思是我稍后应该使用:Session::get('name') 来获取这些项目。

You can try the following code:您可以尝试以下代码:

$name = Input::get('name');
$input = Input::all();
$items = Session::get($name, []);
foreach ($input[$name] as $key => $corporate) {
  $file_name = $key.'_'.$current_time . '_' . $corporate->getClientOriginalName();
  if (!array_key_exists($key, $items)) {
      $items[$key] = [];
  }
  $items[$key][] = $file_name;
}
Session::put($name, $items);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM