繁体   English   中英

检查php中数组是否存在数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM