【问题标题】:Check if value exists in multidimensional array and edit other value inside same key检查多维数组中是否存在值并编辑同一键内的其他值
【发布时间】:2018-03-07 13:41:46
【问题描述】:

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

我的数组如下所示:

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";
}

【问题讨论】:

    标签: php arrays session


    【解决方案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'];
    }
    

    【讨论】:

    • 谢谢,这成功了!所以键现在是产品名称,这样我也可以轻松删除它们。
    • @twan 不客气 :) 如您所见,我已将您对 $_SESSION['cart'] 存在性的测试移到开头,它更易于使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2014-05-28
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多