foreach循环使用in foreach为数组中的每个项在数据库中插入唯一的记录


foreach loop with in foreach to insert unique record in database for each item in array

我有两个数组,一个是关联数组,另一个是非关联数组,我想将每个数组的每个项作为一行插入数据库。在我下面的代码中$menu和$id是数组。这个$id部分给了我错误,因为它本身就是一个数组。。。。错误显示"数组到字符串的转换"。请帮忙!!!

foreach($menu as $label => $link) {
    $id = $request->themeLocation;
    DB::table('menus')->insertGetId([ 'label' => $label ,'url' => $link ,'child_id' =>'child-'.$id ,'menu_status' => 1  ]); 
}

在foreach中应用foreach之后,我将在DB 中获取层次结构条目

       id   child id    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

但是我在数据库中得到了多余的条目,我想要这个结果

       41   child-38    about   ABOUT US    1
       42   child-39    services    Services    1
       43   child-40    contact contact 1

谢谢!!!

如果我明白你想做什么,这将是一种方法:

$i = 0;
$id = $request->themeLocation;
foreach($menu as $label => $link) {
    DB::table('menus')->insertGetId([ 'label' => $label ,'url' => $link ,'child_id' =>'child-'.$id[$i] ,'menu_status' => 1  ]);
    $i++;
}

我知道$id的内容是["38"、"39"、"40"],所以您必须使用数字索引($I)访问其内容。