[英]foreach loop with in foreach to insert unique record in database for each item in array
我有兩個數組,一個是關聯數組,第二個是非關聯數組,我想為每個數組的每一項插入數據庫中的一行。 在我的代碼下面$ menu和$ id是array。 $ 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)訪問其內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.