2016-05-01 40 views
0

我有兩個數組一個是關聯的,第二個是非關聯我想插入每個數組的每個項目作爲數據庫中的一行。在我的代碼下面的$ menu和$ id是數組。這$ ID部分給我錯誤,因爲這本身就是一個數組....錯誤說「數組到字符串轉換」。請幫忙!!!foreach循環與foreach插入數據庫中的每個項目的數據庫的唯一記錄

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

在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 

用的foreach我正在歌廳層次項申請的foreach之後,但我在DB獲得冗餘條目,我想這個結果

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

謝謝!

+0

因此,'$ id = $ request-> themeLocation;'將數字索引數組創建爲'$ id'? – nanocv

回答

0

如果我明白你正在嘗試做的,這將是一個辦法:

$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)訪問其內容。

+0

感謝nanocv !!你讓我的權利.....你給定的解決方案就像一個魅力..非常感謝 –

+0

只是爲了我的經驗,我想知道,如果$ request-> themeLocation沒有數字索引,意味着如果它是聯想指數然後 ??? –

+0

@wasimbeg就是這樣! PHP中有這兩種類型的數組:索引數組(帶數字鍵)和關聯數組(帶有指定鍵)。這裏很好解釋:http://www.w3schools.com/php/php_arrays.asp – nanocv

相關問題