如何检查数组中是否存在值以及是否确实增加了该值

时间:2012-04-25 22:40:40

标签: php

我有以下代码。我希望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;
}

1 个答案:

答案 0 :(得分: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会是更好的关键吗?