【问题标题】:Check if array inside array exists in php检查数组内的数组是否存在于php中
【发布时间】:2018-03-17 02:49:20
【问题描述】:

一次只能退回一种产品。当产品有成分时,我的代码按预期工作。如果没有,我会得到:

未定义的偏移量: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 arrays array-key-exists


    【解决方案1】:

    如果您使用的是 PHP 7+,则无需检查数组的每个维度——您可以在最后一个元素上使用空合并运算符 ??

    if ($response_decoded['products'][0]['ingredients'] ?? null !== null) {
        // ingredients exist
    }
    

    如果该值存在且不为空,则您将陷入该条件。如果数组的任何部分不存在,它将失败,但不会抱怨未定义索引的警告。

    【讨论】:

      猜你喜欢
      • 2014-05-03
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多