[英]php check if element exist through session array
如何循環遍歷會話數組並檢查$_session['items'][1][p_alt-variation-1]
等是否存在? 如果某個項目具有這些附加變體,則[p_alt-variation- {n}]元素是動態的,因此它可能多於1個
的print_r($ _會議[ '項目'])
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
檢查。 如果該關鍵字有多個鍵,則只需計算結果。
這是個主意:
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];
}
}
會話變量就像任何其他數組值一樣; 你總是可以使用isset函數。 請參考: http : //php.net/manual/en/function.isset.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.