检查多维数组中是否存在值,并在同一个键

时间:2018-03-07 13:41:47

标签: php arrays session

我正在尝试检查数组中是否存在值,并且不向其添加全新条目,而只是添加现有数据中的数量。

我的数组看起来像这样:

Array
(
    [0] => Array
        (
            [product] => Douche 1
            [price] => 1200
            [picture] => cms/images/douche.jpg
            [quantity] => 20
        )

    [1] => Array
        (
            [product] => Douche 1
            [price] => 1200
            [picture] => cms/images/douche.jpg
            [quantity] =>  => 18
        )
)

因此要检查值是否存在,我执行了以下操作:

if(in_array('Douche 1', array_column($_SESSION['cart'], 'product'))) { // search value in the array
    echo "FOUND";
}

但是我没有回应FOUND,而是需要以某种方式合并数组,所有数据都保持不变,只有数量需要加起来。

所以当我的数组是这样的时候:

Array
(
    [0] => Array
        (
            [product] => Douche 1
            [price] => 1200
            [picture] => cms/images/douche.jpg
            [quantity] => 20
        )

)

我添加了15个数量的产品,我希望数组更改为:

Array
(
    [0] => Array
        (
            [product] => Douche 1
            [price] => 1200
            [picture] => cms/images/douche.jpg
            [quantity] => 35
        )

)

因此,只有在添加了已存在的产品名称时,数量才会增加,如果它不存在,则只需要一个新密钥(其中包含一个数组)。

我该怎么做?

我现在的整个数组代码(不包括ajax和我的循环)是这样的:

if(isset($_POST['product'])){
  $thisProduct = array(
    'product' => $_POST['product'],
    'price' => $_POST['price'],
    'picture' => $_POST['picture'],
    'quantity' => $_POST['quantity'],
  );
  if (isset($_SESSION['cart'])) {
    $_SESSION['cart'][] = $thisProduct;
  } else {
    //Session is not set, setting session now
    $_SESSION['cart'] = array();
    $_SESSION['cart'][] = $thisProduct;
  }
}

if(in_array('Douche 1', array_column($_SESSION['cart'], 'product'))) { // search value in the array
    echo "FOUND";
}

1 个答案:

答案 0 :(得分:1)

您可以使用产品名称索引数组以检查数组是否存在,而不是在更新cart数组后尝试更改:

$prod = $thisProduct['product'] ; // shortcut for name

if (!isset($_SESSION['cart'])) {
   $_SESSION['cart'] = [] ;
}

if (!isset($_SESSION['cart'][$prod])) { // no exists in cart, add it
   $_SESSION['cart'][$prod] = $thisProduct;
}
else { // exists increment quantity
   $_SESSION['cart'][$prod]['quantity'] += $thisProduct['quantity'];
}