$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;
}
}
}
伙计我有上面的foreach循环来更新会话购物车数组,如果用户点击编辑购物车,但是foreach循环只更新$ session_cart变量数组,它不会更新到$ _SESSION ['cart']。如何在不擦除购物车内其余商品的情况下更新会话购物车内的商品?
答案 0 :(得分:1)
由于$session_cart
未被修改,因此foreach
循环中必须pass it by reference,而$item
也是如此。
此外,=
分配值,而不是==
$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;
答案 1 :(得分:0)
我猜你错误地使用了==
$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;
}
}
}
答案 2 :(得分:0)
$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;
将$item
替换为&$item
references
最后更新$_SESSION['cart']
答案 3 :(得分:0)
用这一行完成你的代码:
$session_cart = unserialize($_SESSION['cart']);
//do smth
$_SESSION['cart'] = serialize($session_cart);
答案 4 :(得分:0)
您使用foreach循环,这就是为什么要修改通过&
创建参考所需的元素的原因$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;
}
}
}
当您执行& item时,它的引用不会被复制,并且引用被修改而不是副本。另请检查您的分配运算符“=”而不是“==”
为了能够直接修改循环中的数组元素,在$ value之前加上&amp ;.在这种情况下,该值将通过引用分配。