我如何遍历一组 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){ ... }
循环所有购物车商品以显示商品信息。
感谢您的建议。
最佳答案
不是正则表达式大师,但您可以使用 preg_grep
获取 key 并进行检查。如果该关键字有多个键,则只计算结果。
思路是这样的:
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];
}
}
关于php通过 session 数组检查元素是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684302/