如何遍历 session 数组集并检查$_session['items'][1][p_alt-variation-1]等是否存在?如果某些项目具有这些附加变体,则[p_alt-variation- {n}]元素是动态的,因此它可能多达1个

print_r($ _ session ['items'])

Array
(
[0] => Array
    (
        [p_name] => Hovid PetSep
        [p_code] => 336910
        [p_coverImg] => 14-1460428610-ulNvG.jpg
        [p_id] => 14
        [p_price] => 24.50
        [p_qty] => 2
    )

[1] => Array
    (
        [p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted)
        [p_code] => 2102649
        [p_coverImg] => 12-1460446199-wI5qx.png
        [p_id] => 12
        [p_price] => 68.00
        [p_alt-variation-1] => Red
        [p_alt-variation-2] => L
        [p_qty] => 1
    )

)

我想向用户显示某些项目是否存在其购物车中的各种变化,如果包含[p_alt-variation- {n}]这样的字符串,如何在数组中查找元素?

我使用foreach($_SESSION['items'] as $cart_item){ ... }循环所有购物车商品以显示商品信息。

谢谢你的建议。

最佳答案

不是正则表达式专家,但是您可以获取 key 并使用preg_grep进行检查。如果该关键字具有多个键,则只需计算结果即可。

这是个主意:

foreach($_SESSION['items'] as $cart_item) { // loop the items
    $keys = array_keys($cart_item); // get the keys of the current batch
    // make the expression
    $matches = preg_grep('~^p_alt\-variation\-\d+~i', $keys); // simply just checking the key name with has a number in the end, adjust to your liking
    if(count($matches) > 1) { // if it has more than one, or just change this to how many do you want
        echo 'has more than one variation';
    }
}

如果您想使用其中一些键,只需使用在$matches内找到的结果:
if(count($matches) > 1) {
    foreach($matches as $matched_key) {
        echo $cart_item[$matched_key];
    }
}

09-25 20:08