0

我有以下代码。我希望elseif零件检查是否$pId已经在数组中,如果是,我想增加它quantityprice不是向$pId数组中添加一个新的。

我不知道我是否使用了错误的方法,或者我的数组结构是否错误,但我无法让它增加这些值

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
    $_SESSION['cart']['pid'][] = $pid;
    $_SESSION['cart']['pid']['price'] = $price;
    $_SESSION['cart']['pid']['quantity'] = $quantity;
    $_SESSION['cart']['total_price'] = $price;
    $_SESSION['cart']['total_items'] = $quantity;
}elseif(array_key_exists($pid, $_SESSION['cart'])){
    //increase price
    //increase quantity
}else{
    $_SESSION['cart']['pid'][] = $pid;
    $_SESSION['cart']['pid']['price'] = $price;
    $_SESSION['cart']['total_price'] += $price;
    $_SESSION['cart']['total_items'] += $quantity;
}
4

1 回答 1

1

我为数组添加了一个额外的维度,以便您可以轻松选择它。

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array('pid' => array(), 'total_price' => 0, 'total_items' => 0);
    $_SESSION['cart']['pid'][$pid] = array();
    $_SESSION['cart']['pid'][$pid]['price'] = $price;
    $_SESSION['cart']['pid'][$pid]['quantity'] = $quantity;
    $_SESSION['cart']['total_price'] = $price;
    $_SESSION['cart']['total_items'] = $quantity;
}elseif(array_key_exists($pid, $_SESSION['cart']['pid'])){
    $_SESSION['cart']['pid'][$pid]['price'] = 'new price';
    $_SESSION['cart']['pid'][$pid]['quantity'] = 'new quantity';
}else{
    $_SESSION['cart']['pid'][$pid]['price'] = $price;
    $_SESSION['cart']['total_price'] += $price;
    $_SESSION['cart']['total_items'] += $quantity;
}

我不知道pid代表什么,但乍一看,它看起来并不具有描述性。也许products会是一个更好的钥匙?

于 2012-04-25T22:50:24.890 回答