【发布时间】: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";
}
【问题讨论】: