【问题标题】:What is the best way to access unknown array elements without generating PHP notice?在不生成 PHP 通知的情况下访问未知数组元素的最佳方法是什么?
【发布时间】:2012-06-02 15:16:15
【问题描述】:

如果我有这个数组,

ini_set('display_errors', true);
error_reporting(E_ALL);

$arr = array(
  'id' => 1234,
  'name' => 'Jack',
  'email' => 'jack@example.com',
  'city' => array(
    'id' => 55,
    'name' => 'Los Angeles',
    'country' => array(
      'id' => 77,
      'name' => 'USA',
     ),
  ),
);

我可以用

得到国家名称
$name = $arr['city']['country']['name'];

但如果国家/地区数组不存在,PHP 会产生警告:

Notice: Undefined index ... on line xxx

我当然可以先做测试:

if (isset($arr['city']['country']['name'])) {
  $name = $arr['city']['country']['name'];
} else {
  $name = '';  // or set to default value;
}

但那是低效的。获得$arr['city']['country']['name'] 的最佳方式是什么? 如果不存在则不生成PHP通知?

【问题讨论】:

  • 为什么会“低效”?
  • 数据从何而来?如果来自第三方,您应该编写一个解析函数来将其解析为一个标准化的数据结构,您知道哪些键存在,哪些不存在......
  • @deceze:获取单个值需要 4 行以上,效率很低。

标签: php


【解决方案1】:

我从 Kohana 那里借用了下面的代码。如果键不存在,它将返回多维数组的元素或 NULL(或选择的任何默认值)。

function _arr($arr, $path, $default = NULL) 
{
  if (!is_array($arr))
    return $default;

  $cursor = $arr;
  $keys = explode('.', $path);

  foreach ($keys as $key) {
    if (isset($cursor[$key])) {
      $cursor = $cursor[$key];
    } else {
      return $default;
    }
  }

  return $cursor;
}

给定上面的输入数组,访问它的元素:

echo _arr($arr, 'id');                    // 1234
echo _arr($arr, 'city.country.name');     // USA
echo _arr($arr, 'city.name');             // Los Angeles
echo _arr($arr, 'city.zip', 'not set');   // not set

【讨论】:

    【解决方案2】:

    @error control operator 抑制表达式生成的任何错误,包括无效的数组键。

    $name = @$arr['city']['country']['name'];
    

    【讨论】:

    • 其实我想写干净的代码,所以我避免@捕捉任何警告和通知并修复它们。
    • 如果您想编写干净的代码,那么您将使用isset(),正如您在问题中所解释的那样。但这很冗长,这就是您寻找替代方案的原因。 @ 是其中最不冗长的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多