我有两个数组,一个是关联的,第二个是非关联的,我想为每个数组的每个项插入数据库中的一行。在我的代码下面$ menu和$ id是数组。这个$ id部分给了我错误,因为它本身就是一个数组....错误说"数组到字符串转换"。请帮忙!!!
foreach($menu as $label => $link) {
$id = $request->themeLocation;
DB::table('menus')->insertGetId([ 'label' => $label ,'url' => $link ,'themeLocation' => '$id ,'menu_status' => 1 ]);
}
id themeLocation url label menu_status
41 child-38 about ABOUT US 1
42 child-39 about ABOUT US 1
43 child-40 about ABOUT US 1
44 child-38 services Services 1
45 child-39 services Services 1
46 child-40 services Services 1
47 child-38 contact contact 1
48 child-39 contact contact 1
49 child-40 contact contact 1
但我在DB中获得冗余条目我想要这个结果
41 child-38 about ABOUT US 1
42 child-39 services Services 1
43 child-40 contact contact 1
感谢!!!
答案 0 :(得分:0)
语法错误是因为=> '$id
中有额外的引用。
如果$id
是一个数组,则需要一个嵌套循环来插入每个值。您应该将数组放在$menu
循环之外,因为它不依赖于该数组中的任何内容。
$locations = $request->themeLocation;
foreach ($menu as $label => $link) {
foreach ($locations as $loc) {
DB::table('menus')->insertGetId([
'label' => $label ,
'url' => $link ,
'themeLocation' => $loc,
'menu_status' => 1 ]);
}
}