繁体   English   中英

Laravel 4从多维会话数组中删除值

[英]Laravel 4 delete a value from a multidimensional session 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)

到目前为止,我已经知道了。 它可以工作,但是必须有更简单的方法。

// 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)

谢谢

您需要循环购物车以能够搜索每个条目的过程值,但可以将其缩短一点。 据我所知, Session::forget()能够通过使用点注释删除数组中的项目。

Session::forget('cart.' . $id);

这就是我要做的:

$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'));

暂无
暂无

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

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