查找多级数组中的哪个索引会在PHP中引发未定义的索引错误

时间:2015-03-03 13:26:06

标签: php arrays

所以我有一个嵌套的php数组,我用它来获取数据:

$this->synthArray[$synthId]['synth_map'][$mapId]['map_sequence'][$gnome];

这一行有时会给我错误undefined index错误。我试图找出哪个索引给出了这个错误 - 我可以在每个级别上做isset()来实现这个目标,但我想知道是否有更简单的方法来找到罪魁祸首......

1 个答案:

答案 0 :(得分:-2)

修改 你的阵列有3个故障点...我的意思是阵列中有3个变量可以不存在。

$this->synthArray[$synthId]['synth_map'][$mapId]['map_sequence'][$gnome];

您可以将其检查为:

if(isset($this->synthArray[$synthId])) {
     if(isset($this->synthArray[$synthId]['synth_map'][$mapId])) {
         if(isset($this->synthArray[$synthId]['synth_map'][$mapId]['map_sequence'][$gnome])) {
             // it's correct
         } else {
             //$gnome is an invalid key
         }
     } else {
          // $mapId is an invalid key
     }
} else {
    // $synthId is an invalid key
}

您可以使用set_error_handler注册自己的错误处理程序。

function errorHandler( $errno, $errstr, $errfile, $errline ) {
    // catch the error here and take action
    echo "{$errstr} in file {$errfile} on line {$errline}"; // example

    /* Don't execute PHP internal error handler */
    return true;
}
set_error_handler('errorHandler');

希望这有帮助。