簡體   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