<?php
require 'header.php';
if (isset ($_POST['id'])) {
$productid = $_POST['id'];
$size = $_POST['size'];
$wasfound = false;
$i = 0;
if (!isset ($_SESSION['cart']) || count($_SESSION['cart']) < 1) {
$_SESSION['cart'] = array (0 => array ("product_id" => $productid, "size" => $size, "quantity" => 1));
}
else {
foreach ($_SESSION['cart'] as $eachitem) {
$i++;
while (list ($key, $value) = each ($eachitem)) {
if (($key == "product_id" && $value == $productid) && ($key == "size" && $value == $size)) {
array_splice ($_SESSION['cart'], $i-1, 1, array (array ("product_id" => $productid, "size" => $size, "quantity" => $eachitem['quantity'] + 1)));
$wasfound = true;
}
}
}
if ($wasfound == false) {
array_push ($_SESSION['cart'], array ("product_id" => $productid, "size" => $size, "quantity" => 1));
}
}
header ("location: cart.php");
exit ();
}
?>
每次我添加product_id相同的id或不同的id,相同的大小或不同的大小,它将是数组上的新索引。我无法在脚本上达到array_splice条件。
我需要使用多个键等于某个值来创建条件。 有人可以帮忙吗?
答案 0 :(得分:0)
foreach ($_SESSION['cart'] as $eachitem) {
//Magic happens here.
if($eachitem["product_id"] == $productId && $eachitem["size"] == $productId ){
array_splice ($_SESSION['cart'], $i-1, 1, array (array ("product_id" => $productid, "size" => $size, "quantity" => $eachitem['quantity'] + 1)));
$wasfound = true;
break;
}
}
如果您只想检查这两个键(product_id和size),它应该可以工作。你可以看到很少的“休息”指令。它就在这里,因为如果我们找到第一场比赛,我们就不需要进一步了解。