0

I've got the following error:

ErrorException: Undefined array key 0 in /Users/User/Sites/Site/app/Jobs/MigrateData.php:67

This is correct in the one instance for my Job, the $this->schools is an empty array and therefore shouldn't be hitting the create. Sorry, I'm a little unsure why this is throwing an error.

    $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']
        ]);
    }

Any help as to where I am going wrong?

lky
  • 1,081
  • 3
  • 15
  • 31
  • 1
    You're always incrementing `$i` but you're only appending to the array when `$dataCode instanceof DataCode`. This could leave "holes" in your array. You probably want to put the `$i++` inside that `if` statement. – Alex Howansky Dec 01 '21 at 17:34
  • The array most likely doesn't have an array key of 0. It might start on 1, 2, or 7, since you're iterating `$i` even if the data isn't added. – aynber Dec 01 '21 at 17:34
  • Do you even need to continue your loop if you found something, since later you are only creating a `first_name` from a single item? Could you just `break` inside your first `if`? – Chris Haas Dec 01 '21 at 18:06
  • Thanks @AlexHowansky, That explains what's happening, I've moved my $i++ and it's working as expected. – lky Dec 02 '21 at 09:14

1 Answers1

0

Load the array like this, it will add a new occurance by using the [] and then add an array to that new occurance

$this->data[] = ['data_id'   => $dataCode->id,
                 'data_name' => $dataCode->name];
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149