Is there any better way to delete a value from this kind of array?
$cart = Session::get('cart):
dd($cart);
// Returns this..
array (size=2)
1 =>
array (size=2)
'border_id' => string '11' (length=2)
'process' => string '516.jpg' (length=7)
2 =>
array (size=2)
'border_id' => string '10' (length=2)
'process' => string '500.jpg' (length=7)
I got this so far. It works but there must be an easier way.
// Look for value:
$process = 516.jpg;
//Search and compare items
$cart = Session::get('cart');
foreach($cart as $key =>$value){
if ($value['process']==$process) {
// Get Index value
$image = $key; }
// Delete Value that as a key of 0
unset($cart[$image]);
Session::forget('cart');
Session::put('cart', $cart);
// Results
dd($cart);
2 =>
array (size=2)
'border_id' => string '10' (length=2)
'process' => string '500.jpg' (length=7)
Thanks
You need to loop the cart to be able to search trough the process value for each entry, but it can be shortened a bit. Session::forget()
is as far as I know able to delete items in an array by using dot annotation.
Session::forget('cart.' . $id);
This is how I would do it:
$process = '500.jpg';
foreach (Session::get('cart', []) as $id => $entries) {
if ($entries['process'] === $process) {
Session::forget('cart.' . $id);
break; // stop loop
}
}
dd(Session::get('cart'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.