[英]Check if array inside array exists in php
一次只能退回一種產品。 當產品具有成分時,我的代碼將按預期工作。 如果沒有,我將得到:
未定義的偏移量:0
它引用了以下代碼行: if ($response_decoded['products'][0]['ingredients'] != null){
我了解這是因為沒有成分,但是有時候是不可避免的。
因此,在這一點上:
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setBody("{body}");
try
{
$response = $request->send();
$result = $response->getBody();
$response_decoded = json_decode($result,true);
print_r($response_decoded);
...我回來了:
Array ( [products] => Array ( [0] => Array ( [gtin] => 05052909299653 [tpnb] => 065738756 [tpnc] => 272043262 [description] => Tesco Lemon And Lime Zero 2L [brand] => TESCO [qtyContents] => Array ( [quantity] => 2000 [totalQuantity] => 2000 [quantityUom] => ml [netContents] => 2L e ) [productCharacteristics] => Array ( [isFood] => [isDrink] => 1 [healthScore] => 70 [isHazardous] => [storageType] => Ambient [isNonLiquidAnalgesic] => [containsLoperamide] => ) [ingredients] => Array ( [0] => Carbonated Water [1] => Citric Acid [2] =>
等等...
然后,我做:
// check for ingredient array
if ($response_decoded['products'][0]['ingredients'] != null){
// can now target ingredient array
$ingredients = $response_decoded['products'][0]['ingredients'];
因此,我相信不僅需要!= null
需要事先檢查“成分”是否存在。 我雖然可以使用array_key_exists
來做到這一點。
if (array_key_exists('products', $response_decoded)) {
echo "Product is there";
}
else{
echo "Product is not there";
}
現在工作了,它告訴我產品是否存在...但是如何檢查產品成分是否存在?
如果您使用的是PHP 7+,則無需檢查數組的每個維度-您可以使用null合並運算符??
在最后一個元素上:
if ($response_decoded['products'][0]['ingredients'] ?? null !== null) {
// ingredients exist
}
如果該值存在並且不為null,那么您將陷入該狀況。 如果數組的任何部分不存在,它將失敗,但不會抱怨未定義索引的警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.