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


Find which index in a multi level array throws undefined index error in PHP

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

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

这行有时会给我错误undefined index错误。我正试图弄清楚哪个索引会产生错误——我可以在每个级别上执行isset()来实现这一点,但我想知道是否有更容易的方法来找到罪魁祸首。。。

编辑你的数组有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');

希望这能有所帮助。