如何遍历数组并将其值存储在Laravel中

时间:2019-09-27 07:01:47

标签: php laravel

我有以下数组:

$catprefs = $request['catpref'];

Vardump:

array(5) { [0]=> string(1) "1" [1]=> string(2) "11" [2]=> string(1) "2" [3]=> string(1) "3" [4]=> string(1) "4" }

我需要循环该数组并将每个值存储在新行中,如下所示:

foreach ($catprefs as $save_catp) {
      $save_catp = new Cpref();
      $save_catp->user_id = $user_id;
      $save_catp->qatype = ????? ; // need to put the array value here
      $save_catp->type = 1;

      $save_catp->save();
}    

如何在上面的插入中存储数组的每个值?

4 个答案:

答案 0 :(得分:2)

尝试一下。

foreach($catprefs as $save_catp){

      $cpref= new Cpref();
      $cpref->user_id = $user_id;
      $cpref->qatype = $save_catp; // need to put the array value here
      $cpref->type = 1;
      $cpref->save();

}

如果您使用$key => $value

foreach($catprefs as $key => $value){

      $cpref= new Cpref();
      $cpref->user_id = $user_id;
      $cpref->qatype = $value; // need to put the array value here
      $cpref->type = 1;
      $cpref->save();

}

答案 1 :(得分:2)

if(!empty($catprefs))
{
 foreach($catprefs as $key => $row)
 {
   $save_catp = new Cpref();
   $save_catp->user_id = $user_id;
   $save_catp->qatype = $row ; // need to put the array value here
   $save_catp->type = 1;
   $save_catp->save();
 } 
}

答案 2 :(得分:2)

您还可以如下使用批量插入内容:

df1 <- structure(list(ID = c("130239", "130241", "130244", "130250_2", 
 "130313_2", "130248_2", "130308_3")), class = "data.frame", 
  row.names = c(NA, -7L))

答案 3 :(得分:1)

foreach($catprefs as $save_catp){
$save_catp = new Cpref();

您在for循环和Cpref对象中使用$save_catp,需要更改其中一个变量。

if(!empty($catprefs)){
  foreach($catprefs as $key => $val){

  $save_catp = new Cpref();
  $save_catp->user_id = $user_id;
  $save_catp->qatype = $val; // array value goes here
  $save_catp->type = 1;


  $save_catp->save();

 } 
}