我有一个会话cookie,其中包含一个名为cart_array的多维数组,我正在使用a来循环遍历内部数组,而while循环则获取键值对。
我想检查一个项目是否存在于数组中,不仅基于产品ID(pid),还有其他几个变量,如颜色和大小。这是我到目前为止所提出的(但它只检查pid)。如何检查其他两个变量?
这是我的变量
$_SESSION['cart_array'] = array(1 => array(
"pid" => $pid,
"quantity" => $quantity,
"color" => $color,
"size" => $size,
"title" => $title,
"product_type" => $product_type,
"price" => $price))
以下是for循环组合的代码:
foreach($_SESSION['cart_array'] as $each_item) {
$index++;
while(list($key, $value) = each($each_item)) {
if($key == "pid" && $value == $pid) {
//That item is in the array
echo "This item is in the array";
} else {
echo "This item is not in the cart";
}
}
}
答案 0 :(得分:0)
我会做这样的事情:
foreach($_SESSION['cart_array'] as $each_item) {
$index++;
$pidTest = false;
$colorTest = false;
$sizeTest = false;
while(list($key, $value) = each($each_item)) {
if($key == "pid" && $value == $pid) {
$pidTest = true;
}
if($key == "color" && $value == $color) {
$colorTest = true;
}
}
if ($pidTest && $colorTest && sizeTest)
{
echo "Item is in the cart";
}
else
{
echo "Nope";
}
}
当然,你可以更优雅,更动态地处理这个问题,但这是你可以使用的基本逻辑。
答案 1 :(得分:0)
你试过了吗?
foreach($_SESSION['cart_array'] as $item) {
$index++;
$pid_matches = $color_matches = $size_matches = false;
foreach($item as $key => $value) {
if($key == 'pid' && $value == $pid) {
$pid_matches = true;
}
elseif($key == 'color' && $value == $color){
$color_matches = true;
}
elseif($key == 'size' && $value == $size){
$size_matches = true;
}
}
if($pid_matches && $color_matches && $size_matches){
echo "This item is in the array";
}
else {
echo "This item is not in the cart";
}
}
答案 2 :(得分:0)
如果我找对你,这可能会有所帮助:
$_SESSION['cart_array'] = array(1 => array(
"pid" => $pid,
"quantity" => $quantity,
"color" => $color,
"size" => $size,
"title" => $title,
"product_type" => $product_type,
"price" => $price));
foreach($_SESSION['cart_array'] as $item) {
foreach($item as $key => $value) {
if( empty($value) ) {
echo "This item is not in the cart";
continue 2;
}
}
echo "This item is in the cart";
}
这将检查您商品的每个字段。如果您需要包含一组排除项的解决方案,或者您需要将元素与一组值进行比较 - 请在评论中告诉我。