【发布时间】:2015-05-31 13:07:45
【问题描述】:
<?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 条件。
我需要使多个键的条件等于某个值。 有人可以帮忙吗?
【问题讨论】:
-
"($key == "product_id" && $value == $productid) && ($key == "size" && $value == $size)" -这一刻对我来说很奇怪.您的意思是“或”(||)而不是“和”(&&)。如果 key 等于“product_id”,则它不能是“size”。看起来像“薛定谔字符串”:)
-
如果我想用多个key来做条件,并且值等于某个值,怎么做?
标签: php arrays if-statement splice