Reputation: 39
$session_cart = $_SESSION['cart'];
foreach($session_cart as $item){
foreach($item as $item2){
if($item2['subject'] == "2014 ICAS - Computer Skills"){
$item2['quantity'] == $sum;
$item2['total'] == $total;
$item2['level'] == $newlevelarray;
}
}
}
Guys I have the foreach loop above to update the session cart array if user click edit cart, but the foreach loop only updates the $session_cart variable array, it doesn't update to $_SESSION['cart']. How to update item inside the session cart without wiping the rest of the item inside the cart?
Upvotes: 0
Views: 106
Reputation: 3387
Since $session_cart
isn't modified, you have to pass it by reference in your foreach
loop, and the same goes for $item
.
Also, it's =
to assign values, not ==
$session_cart = $_SESSION['cart'];
foreach($session_cart as &$item){
foreach($item as &$item2){
if($item2['subject'] == "2014 ICAS - Computer Skills"){
$item2['quantity'] = $sum;
$item2['total'] = $total;
$item2['level'] = $newlevelarray;
}
}
}
$_SESSION['cart'] = $session_cart;
Upvotes: 1
Reputation: 1463
finish your code with this line:
$session_cart = unserialize($_SESSION['cart']);
//do smth
$_SESSION['cart'] = serialize($session_cart);
Upvotes: 0
Reputation: 6066
$session_cart = $_SESSION['cart'];
foreach($session_cart as &$item){
foreach($item as &$item2){
if($item2['subject'] == "2014 ICAS - Computer Skills"){
$item2['quantity'] = $sum;
$item2['total'] = $total;
$item2['level'] = $newlevelarray;
}
}
}
$_SESSION['cart'] = $session_cart;
replaced $item
with &$item
references
updated $_SESSION['cart']
at the end
Upvotes: 0
Reputation: 20286
You use foreach loop that is why to modify elements you need to create reference via &
$session_cart = $_SESSION['cart'];
foreach($session_cart as &$item){
foreach($item as &$item2){
if($item2['subject'] == "2014 ICAS - Computer Skills"){
$item2['quantity'] = $sum;
$item2['total'] = $total;
$item2['level'] = $newlevelarray;
}
}
}
When you do as &item then it's referenced not copied and the reference is modified not the copy. Also check your assigment operator which is "=" not "=="
From PHP manual
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Upvotes: 0
Reputation: 7240
I guess you are mistakenly using ==
$session_cart = $_SESSION['cart'];
foreach($session_cart as $item){
foreach($item as $item2){
if($item2['subject'] == "2014 ICAS - Computer Skills"){
$item2['quantity'] = $sum;
$item2['total'] = $total;
$item2['level'] = $newlevelarray;
}
}
}
Upvotes: 0