为什么在检查未定义索引是否为空时会抛出错误?

Why am I throw an error for undefined index when I'm checking whether it's empty?

提问人:lky 提问时间:12/2/2021 更新时间:12/2/2021 访问量:189

问:

我收到以下错误:

错误异常:/Users/User/Sites/Site/app/Jobs/MigrateData.php:67 中未定义的数组键 0

这在我的工作的一个实例中是正确的,$this->schools 是一个空数组,因此不应该点击创建。对不起,我有点不确定为什么会抛出错误。

    $this->data = [];

    $i=0;
    foreach($core_data as $core) {

        $dataCode = DataCode::where('code', $core->code)->first();

        if ($dataCode instanceof DataCode) {
            $this->data[$i]['data_id'] = $dataCode->id;
            $this->data[$i]['data_name'] = $dataCode->name;
        }

        $i++;
    }

    if (!empty($this->data)) {
        $data = Data::create([
            'first_name' => $this->data[0]['data_name']
        ]);
    }

对我哪里出错有什么帮助吗?

php 数组 is-empty undefined-index

评论

1赞 Alex Howansky 12/2/2021
您总是在递增,但只有在 .这可能会在数组中留下“漏洞”。你可能想把这句话放在里面。$i$dataCode instanceof DataCode$i++if
0赞 aynber 12/2/2021
该数组很可能没有 0 的数组键。它可能从 1、2 或 7 开始,因为即使未添加数据,您也在迭代。$i
0赞 Chris Haas 12/2/2021
如果你发现了一些东西,你甚至需要继续你的循环,因为以后你只是从单个项目创建一个?你能在你的第一个里面吗?first_namebreakif
0赞 lky 12/2/2021
谢谢@AlexHowansky,这解释了发生了什么,我已经移动了我的 $i++,它按预期工作。

答:

0赞 RiggsFolly 12/2/2021 #1

像这样加载数组,它将使用 添加一个新事件,然后将数组添加到该新事件中[]

$this->data[] = ['data_id'   => $dataCode->id,
                 'data_name' => $dataCode->name];