Rajes
Rajes

Reputation: 103

Split array and insert to database in laravel

I have array like this

$group=[['abc','cde','01/03/2019','01/05/2019'],['123','456','01/23/2019','01/30/2019']];

I want to insert to database by 4 field like this:

field1     field2      field3        field4
 abc         cde     01/03/2019    01/05/2019
 123         456     01/23/2019    01/30/2019

I try these code:

for($j=1;$j<count($groups);$j++){
    for ($k=0; $k < count($groups[$j]) ; $k++) { 
        $insert = array(
           'activity' => $groups[$j][$k],
           'person' => $groups[$j][$k],
           'startdate' => $groups[$j][$k],
           'finishdate' => $groups[$j][$k]
        );
    DB::table('test_tbl')->insert($insert);
    }
}

any solution for this thank you

Upvotes: 0

Views: 638

Answers (4)

Shobi
Shobi

Reputation: 11461

use array_map()

array_map(function($item){
   DB::table('table_name')->insert([
      'activity'   => $item[0],
      'person'     => $item[1],
      'startdate'  => $item[2],
      'finishdate' => $item[3]
   ]);
}, $groups);

Upvotes: 0

Petay87
Petay87

Reputation: 1773

Foreach

I would suggest you make use of the ForEach loop:

foreach($group as $item){
  $insert = array(
    'activity' => $item[0],
    'person' => $item[1],
    'startdate' => $item[2],
    'finishdate' => $item[3]
  );

  DB::table('test_tbl')->insert($insert);

}

This way you don't need to count the array and the code is nice and tidy.

Upvotes: 1

Doseq
Doseq

Reputation: 233

How about foreach?

foreach ($group as $item){
  $insert = array(
           'activity' => $item[0],
           'person' => $item[1],
           'startdate' => $item[2],
           'finishdate' => $item[3]
        );
    DB::table('test_tbl')->insert($insert);
    }
}

Upvotes: 1

Joseph_J
Joseph_J

Reputation: 3669

I think the easiest way in this case would just be to hard code your indexes.

Like so:

for($j = 0;  $j  < count($groups); $j++){

  $insert = array(
    'activity' => $groups[$j][0],
    'person' => $groups[$j][1],
    'startdate' => $groups[$j][2],
    'finishdate' => $groups[$j][3]
  );

  DB::table('test_tbl')->insert($insert);

}

In a FOR loop your index counter $j will generally start at 0. So be careful with that going forward.

Upvotes: 1

Related Questions