问题描述
这是我参加会议的问题
session('products')
这实际上是一个包含id的数组
this is actually an array that contains id
session('products')
array:4 [▼
0 => "1"
1 => "2"
2 => "4"
3 => "1"
]
现在我要删除,说4
,我该怎么做?我尝试过方法
Now I want to delete lets say 4
How do I do that? I tried method
session()->pull($product, 'products');
但是没有用!
其他解决方案
session()->forget('products', $product);
它也不起作用
推荐答案
AFAIR必须首先检索整个数组,对其进行编辑,然后再次进行设置.如果要按产品ID删除(这是我假定的数组值),则可以使用以下方法:
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)
$products = session()->pull('products', []); // Second argument is a default value
if(($key = array_search($idToDelete, $products)) !== false) {
unset($products[$key]);
}
session()->put('products', $products);
被误解的问题
Session::pull
将第一个参数作为要删除的项目,将第二个参数作为要返回的默认值.您弄错了参数的顺序.试试:
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('products'); // You can specify second argument if you need default value
正如我在源代码中看到的,Session::forget
需要字符串或数组,因此您应仅指定第一个参数:
As I can see in source, Session::forget
expects string or array, so you should specify only the first parameter:
session()->forget('products');
这篇关于如何从Laravel中的会话数组中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!