Continue inserting data from multiples arrays even if one of them is empty

  laravel, mysql, php

I’m creating a kind of multilingual dictionary with words from different languages on the same row with php, mysql and laravel. I insert the data from arrays with different length with a for loop. My problem is that the loop will stop as soon as one of the arrays is empty. I’d like to continue inserting data as long as all the arrays aren’t empty, even if it means that some columns will be NULL in the database.

$words = request()->json()->all();
$base_words = array_column($words, 'baseForm');
$fr = array_column($words, 'fr');
$en = array_column($words, 'en');
$es = array_column($words, 'es');
$it = array_column($words, 'it');
$de = array_column($words, 'de');

for ($i = 0; $i < max($fr, $en, $es, $it, $de); $i++) {
  Word::insert([
    'ru' => $base_words[$i],
    'fr' => $fr[$i],
    'en' => $en[$i],
    'es' => $es[$i],
    'it' => $it[$i],
    'de' => $de[$i]
  ]);
}

Here is how my $words array looks like with dd() (I deleted some entries or the array would have been to long).

array:56 [
  0 => array:2 [
    "baseForm" => "да"
    "es" => "sí"
  ]
  1 => array:2 [
    "baseForm" => "да"
    "es" => "y"
  ]
  15 => array:2 [
    "baseForm" => "да"
    "it" => "e"
  ]
  20 => array:2 [
    "baseForm" => "да"
    "fr" => "oui"
  ]
  28 => array:2 [
    "baseForm" => "да"
    "en" => "yes"
  ]
  29 => array:2 [
    "baseForm" => "да"
    "en" => "yeah"
  ]
]

Thanks in advance to anyone who would like to help me on this.

Source: Laravel

Leave a Reply