【问题标题】:Why am I throw an error for undefined index when I'm checking whether it's empty?为什么在检查未定义索引是否为空时会引发错误?
【发布时间】:2022-01-08 07:27:19
【问题描述】:

我遇到以下错误:

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

这在我的 Job 的一个实例中是正确的,$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']
        ]);
    }

对我哪里出错有帮助吗?

【问题讨论】:

  • 你总是在递增$i,但你只是在$dataCode instanceof DataCode时附加到数组中。这可能会在您的阵列中留下“漏洞”。您可能希望将 $i++ 放在 if 语句中。
  • 该数组很可能没有数组键 0。它可能从 1、2 或 7 开始,因为即使没有添加数据,您也在迭代 $i
  • 如果你找到了一些东西,你甚至需要继续你的循环吗,因为稍后你只是从单个项目创建一个first_name?你能把break放在你的第一个if里面吗?
  • 谢谢@AlexHowansky,这解释了发生了什么,我已经移动了我的 $i++ 并且它按预期工作。

标签: php arrays is-empty undefined-index


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多