我是php的初学者,如果您觉得这个问题有点奇怪,请道歉。
我正在尝试检查我POST并存储在会话数组中的2个变量。 2个变量是购物车中商品的尺寸和颜色。
如何检查会话数组中是否已存在这两个变量。如果是这种情况我只想增加数量。事实上,我认为我只是缺少编写我的if语句来检查这种情况。这是代码:
if (isset($_POST['ID']) && isset($_POST['SIZE']) && isset($_POST['COLOR'])) {
$product = $_POST['ID'];
$size = $_POST['SIZE'];
$color = $_POST['COLOR'];
$Found = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["myArray"]) || count($_SESSION["myArray"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["myArray"] = array(0 => array("productID" => $product, "quantity" => 1, "size"=> $size, "color" => $color));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["myArray"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item))
{
if (($key == "productID" && $value == $product))//<- IT'S PROBABLY WHERE I SHOULD CHECK THEM BUT HOW????
{
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["myArray"], $i-1, 1, array(array("productID" => $product, "quantity" => $each_item['quantity'] + 1, "size"=> $size, "color" => $color)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($Found == false) {
array_push($_SESSION["myArray"], array("productID" => $product, "quantity" => 1, "size"=> $size, "color" => $color));
}
}
}
提前感谢您的帮助。
答案 0 :(得分:0)
您需要列出数组的键和值吗?
foreach ($_SESSION["myArray"] as $key=>$each_item) {
如何检查我的这两个变量是否已经存在 会话数组。
if(array_key_exist('color',$_SESSION["myArray"]))
答案 1 :(得分:0)
我想你需要更轻松的东西(在我看来,myArray似乎是个坏名字):
$product_id = $_POST['ID']; //You should sanitize this input!
if(array_key_exist($product_id,$_SESSION["myCart"])) {
$_SESSION["myCart"][$product_id]['quantity']++;
} else {
$size = $_POST['SIZE']; //Sanitize this input as well
$color = $_POST['color'];
$_SESSION["myCart"][$product_id] = array(
'size' => $size,
'color' => $color,
'quantity' => 1,
);
}
希望有所帮助:)