我有2个变量,我们走了:
@name = array('a','b','c');
@age = array('1','2','3');
然后我想插入列name
值a
和列age
值1
并循环直到数组的末尾。
我尝试使用这个但没有意义:
$t = count($name);
DB::table('users')->insert(array(
for ($i=0; $i < $t ; $i++) {
}
array('name' => $name.$i, 'dob' => $dob.$i)
));
我该如何解决?
答案 0 :(得分:0)
这样:
$name = 'whatever name - ';
$age = 'whatever age - ';
foreach(range(1,3) as $i)
{
DB::table('users')->insert(
array('name' => $name.$i, 'dob' => $dob.$i)
);
}
或者,拥有你的阵列:
$names = array('a','b','c');
$ages = array('1','2','3');
foreach($names as $name)
{
foreach($ages as $age)
{
DB::table('users')->insert(
array('name' => $name, 'age' => $age)
);
}
}
答案 1 :(得分:0)
if u want to insert
name age
a 1
b 2
c 3
like this then use following code
$names = array('a','b','c');
$ages = array('1','2','3');
foreach($names as $index => $name)
{
$data=array('name' => $name, 'age' => $ages[$index]);
DB::table('users')->insert($data);
}
if u want to insert
name age
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
like this then use following code
$names = array('a','b','c');
$ages = array('1','2','3');
foreach($names as $name)
{
foreach($ages $age){
$data=array('name' => $name,'age' => $age);
DB::table('users')->insert($data);
}
}
答案 2 :(得分:0)
创建数组数组:
$data = array();
foreach($names as $index => $name)
{
$item = array('name' => $name, 'age' => $ages[$index]);
array_push($data,$item);
}
Users::insert($data); // Eloquent
OR
DB::table('users')->insert($data); //Insert all rows