如果Key Value对存在于多维数组中。如何?

时间:2012-11-24 22:37:07

标签: php codeigniter loops

我有一个codeigniter购物车,其“cart”数组如下:

Array (
[a87ff679a2f3e71d9181a67b7542122c] => Array
    (
        [rowid] => a87ff679a2f3e71d9181a67b7542122c
        [id] => 4
        [qty] => 1
        [price] => 12.95
        [name] => Maroon Choir Stole
        [image] => 2353463627maroon_3.jpg
        [custprod] => 0
        [subtotal] => 12.95
    )

[8f14e45fceea167a5a36dedd4bea2543] => Array
    (
        [rowid] => 8f14e45fceea167a5a36dedd4bea2543
        [id] => 7
        [qty] => 1
        [price] => 12.95
        [name] => Shiny Red Choir Stole
        [image] => 2899638984red_vstole_1.jpg
        [custprod] => 0
        [subtotal] => 12.95
    )

[eccbc87e4b5ce2fe28308fd9f2a7baf3] => Array
    (
        [rowid] => eccbc87e4b5ce2fe28308fd9f2a7baf3
        [id] => 3
        [qty] => 1
        [price] => 14.95
        [name] => Royal Blue Choir Stole
        [image] => 1270984005royal_vstole.jpg
        [custprod] => 1
        [subtotal] => 14.95
    )

我的目标是在这个多维数组中循环一些如何以及如果任何具有键值对“custprod == 1”的产品存在,那么我的结帐页面将显示一件事,如果购物车中没有自定义产品显示另一件事。任何帮助表示赞赏。感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用array_key_exists检查custprod密钥,而不是对其进行循环。或者只是查看arr['custprod'] isset(两个函数是否以不同的方式处理null)。

$key = "custprod";
$arr = Array(
    "custprod" => 1, 
    "someprop" => 23
);
if (array_key_exists($key, $arr) && 1 == $arr[$key]) {
    // 'custprod' exists and is 1
}

答案 1 :(得分:1)

function item_exists($cart, $custprod) {
    foreach($cart as $item) {
        if(array_key_exists("custprod", $item) && $item["custprod"] == $custprod) {
            return true;
        }
    }
    return false;
}

现在,您可以使用此功能检查产品是否存在于堆栈中:

if(item_exists($cart, 1)) {
    // true
} else {
   // false
}

答案 2 :(得分:0)

你仍然需要循环数组来检查它:

$cust_prod_found = false;

foreach($this->cart->contents() as $item){
    if (array_key_exists("custprod", $item) && 1 == $item["custprod"]) {
        $cust_prod_found = true; break;
    }
}

if ($cust_prod_found) {
    // display one thing
} else {
    // display another thing
}
相关问题