Php 如何循环遍历数组并将其值存储在Laravel中
我有以下数组:Php 如何循环遍历数组并将其值存储在Laravel中,php,laravel,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\u catp){ $save_catp
$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\u catp){
$save_catp=new Cpref();
$save\u catp->user\u id=$user\u id;
$save_catp->qatype=?????;//需要将数组值放在这里
$save_catp->type=1;
$save_catp->save();
}
如何在上面的插入中存储数组的每个值?试试这个
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();
}
如果在for循环和Cpref对象中使用$save\u 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();
}
}
您还可以按如下方式使用批量插入:
$data = [];
foreach($catprefs as $key => $val){
$data[] =[
'user_id' => $user_id,
'qatype' => $val,
'type' => 1
]
}
Cpref::insert($data);
我收到此错误:方法App\Cpref::\uuuu toString()必须返回字符串值数据库中的字段是smallintEdited答案请立即重试。是否可以创建对象
new Cpref()代码>只有一次循环外?是的,@Yasin Patel给出了答案下面的答案<代码>Cpref::插入($data)代码>使用数组,您可以执行此操作。当前有什么不起作用?
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();
}
}
$data = [];
foreach($catprefs as $key => $val){
$data[] =[
'user_id' => $user_id,
'qatype' => $val,
'type' => 1
]
}
Cpref::insert($data);