2016-05-01 29 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

相关问题