请问如何增加关联数组中特定键的值?
我在做以下但似乎没有工作。 谢谢。
$_SESSION['cart_items'] = ["a" => 1, "b" => 1];
$product_id can be a or b.
foreach ($_SESSION['cart_items'] AS $id => $quantity){
if ($id == $product_id){
$_SESSION[$product_id][$quantity] +=1;
}
}
答案 0 :(得分:2)
只做
$_SESSION['cart_items'][$product_id]++;
答案 1 :(得分:1)
您可以测试代码:
<?php
// start the session and avoid notice
@session_start();
// if not set session for cart_items, set first
if ( ! isset($_SESSION['cart_items'])) {
// this is session data with product details
$_SESSION['cart_items'] = array("a" => 1, "b" => 1);
}
// assuming if product is 'a'
$product_id = $_GET['product_name'];
// check if product 'a' exist in SESSION as KEY then add +1
if (isset($_SESSION['cart_items'][$product_id])) {
$_SESSION['cart_items'][$product_id]++;
}
// debug value of SESSION
echo '<pre>', print_r($_SESSION, true), '</pre>';
// run this code after save in file e.g. test.php?product_name=a or text.php?product_name=b
?>
答案 2 :(得分:0)
或者您也可以这样做:
$_SESSION[$product_id] = parseInt($quantity) + 1;