简体   繁体   English

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

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

I have two arrays one is associative and second one is non associative i want to insert for each item of each array as a row in the database. 我有两个数组,一个是关联数组,第二个是非关联数组,我想为每个数组的每一项插入数据库中的一行。 In my code below $menu and $id are array . 在我的代码下面$ menu和$ id是array。 This $id part is giving me error as this itself is an array .... error says "array to string conversion". $ id这部分给我错误,因为它本身是一个数组..错误显示为“数组到字符串的转换”。 Please help!!! 请帮忙!!!

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

after applying foreach with in foreach i am geting hierarchy entries in DB 在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

but i am getting redundant entries in DB i want this result 但是我在数据库中得到多余的条目

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

Thanks!!! 谢谢!!!

If I understood what you are trying to do, this would be a way: 如果我了解您要执行的操作,则可以采用以下方法:

$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++;
}

I understand $id content is ["38", "39", "40"], so you have to access to its content with a numeric index ($i). 我了解$id内容为[“ 38”,“ 39”,“ 40”],因此您必须使用数字索引($ i)访问其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM