为什么此数组中存在未定义的偏移量


Why there is an undefined offset in this array?

我想在一个名为$temp的数组中存储一些数据,但我遇到了一个错误,即有一个未定义的偏移量。这是我的代码:

$temp    = array();
$terms   = $this->DocumentTerms();
$temp[0] = $terms[0][0];
for ($i = 0; $i < sizeof($terms); $i++) {
    $flag = true;
    for ($j = 0; $j < sizeof($terms[$i]); $j++) {
        for ($k = 0; $k < sizeof($temp) || $k < sizeof($terms[$i]); $k++) {
            if ($temp[$k] == $terms[$i][$j]) {
                $flag = false;
                break;
            }
        }
        if ($flag)
            array_push($temp, $terms[$i][$j]);
    }
}

未定义的偏移量在此部分:

if($temp[$k] == $terms[$i][$j])

此条件:

$temp[$k] == $terms[$i][$j]

应为:

isset($temp[$k]) && $temp[$k] == $terms[$i][$j]

直到第二个循环结束,您才将任何数据推送到$temp,但您尝试访问此条件中数组的第$k个索引。如果它还没有设置,它就会失败。检查以确保它已设置,然后继续查看它是否等于$terms[$i][$j]