一次只能退回一种产品。当产品有成分时,我的代码按预期工作。如果没有,我会得到:
未定义的偏移量: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";
}
现在可以了,它会告诉我产品是否存在……但是如何检查产品的成分是否存在?