如何从 Laravel 的会话数组中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42609844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an item from session array in laravel
提问by Alen
Here is the problem I have a session
这是我有一个会话的问题
session('products')
this is actually an array that contains id
这实际上是一个包含 id 的数组
session('products')
array:4 [▼
0 => "1"
1 => "2"
2 => "4"
3 => "1"
]
Now I want to delete lets say 4
How do I do that? I tried method
现在我想删除让我们说4
我该怎么做?我试过方法
session()->pull($product, 'products');
But it didn't work!
但它没有用!
Other solution
其他解决方案
session()->forget('products', $product);
it also didn't work
它也没有用
回答by Albert221
You AFAIR have to firstly retrieve whole array, edit it and then set it again. If you want to delete by product ID, which is as I assume an array value, you can use this: PHP array delete by value (not key)
您 AFAIR 必须首先检索整个数组,对其进行编辑,然后再次设置。如果你想按产品 ID 删除,我假设一个数组值,你可以使用这个:PHP array delete by value (not key)
$products = session()->pull('products', []); // Second argument is a default value
if(($key = array_search($idToDelete, $products)) !== false) {
unset($products[$key]);
}
session()->put('products', $products);
Misunderstood question
被误解的问题
Session::pull
takes first parameter as the item do delete and second as the default value to return. You have mistaken the order of arguments. Try:
Session::pull
将第一个参数作为项目 do delete 和第二个作为要返回的默认值。你弄错了参数的顺序。尝试:
session()->pull('products'); // You can specify second argument if you need default value
As I can see in source, Session::forget
expects string or array, so you should specify only the first parameter:
正如我在source中看到的,Session::forget
需要字符串或数组,所以你应该只指定第一个参数:
session()->forget('products');
回答by Ан?елкоски Бо?ан
This method isn't tested:
此方法未经测试:
Session::forget('products.' . $i);
note the dot notation here, its worth the try. If that isnt working, you can always do this:
注意这里的点符号,值得一试。如果那不起作用,您可以随时执行以下操作:
$products = Session::get('products'); // Get the array
unset($product[$index]); // Unset the index you want
Session::set('products', $products); // Set the array again