PHP中最简洁的方法是测试数组密钥是否存在并保存它的值?

时间:2012-05-10 19:06:01

标签: php arrays simplexml

这看起来很笨重:

if (empty($xml['soap:Envelope']['soap:Body']['SendPurchasesResponse']['PurchasesResponse']['Status']['Code'])) {
    $status = $xml['soap:Envelope']['soap:Body']['SendPurchasesResponse']['PurchasesResponse']['Status']['Code'];
}

如果缺少某些数组键,是否有更好的方法来处理“未定义的索引”错误?正如您可能猜到的,这个数组来自基于XML的API,我不相信他们对我的回应。

你认为使用“@”使用抑制错误是一个警察:

$status = @$xml['soap:Envelope']['soap:Body']['SendPurchasesResponse']['PurchasesResponse']['Status']['Code'];

1 个答案:

答案 0 :(得分:0)

这对你有什么用?

try {
  $status = $xml['soap:Envelope']['soap:Body']['SendPurchasesResponse']['PurchasesResponse']['Status']['Code'];
} catch (Exception $e) {
  $status = ""
}