找不到数组索引为零的值


Can not find value with array index of zero

我有以下方法:

protected function find($obj, $path){
    for($i = 0, $path = preg_split('/['[']'.]/', $path), $len = count($path); $i < $len; $i++){
        if($path[$i]){
            $item = ctype_digit($path[$i]) ? (int)$path[$i] : $path[$i];
            if(is_object($obj)){
                $obj = $obj->$item;
            }else{
                $obj = $obj[$item];
            }
        }
    }
    return $obj;
}

我可以传递一个对象和一个字符串给它,它通常会找到它。我遇到过一个不工作的情况。

$data->name = [
    [
        'first' => 'Fred',
        'last'  => 'Hanks'
    ],
    [
        'first' => 'Tim',
        'last'  => 'Duncan'
    ]
];
$obj->find($data, 'name[0].first');
$obj->find($data, 'name[1].first');

执行此操作时,由于某种原因,第一个查找不起作用,而第二个查找可以。

第一个find()给了我这个错误:

未定义索引:first

但是第二个find()给了我Tim。为什么第二个成功了,而第一个失败了?

因为当要求if( $path[$i])时,"0"被认为是false

看起来if语句是为了删除空匹配(例如].之间的匹配)。在本例中,使用if( $path[$i] == "") continue;更显式地跳过空字符串值。