我有一个多维数组,表格如下:
$items = array:8 [▼
"units" => array:4 [▼
0 => "1"
1 => "1"
2 => "1"
3 => "1"
]
"article_group" => array:4 [▼
0 => "2401"
1 => "2503"
2 => "1360"
3 => "1198"
]
"article" => array:4 [▶]
"description_en" => array:4 [▶]
"unit_price" => array:4 [▶]
"discount" => array:4 [▶]
"invoice" => array:4 [▶]
"delivery_note" => array:4 [▶]
]
表单是动态生成的,并不总是包含4个值,但它们总是包含相同数量的值。
我想要做的是将这些记录保存在mysql数据库中,如下所示:
$bookingDetails = new bookingDetails;
$bookingDetails->units = units[0];
$bookingDetails->article_group = article_group[0];
$bookingDetails->article = article[0];
$bookingDetails->description_en = description_en[0];
$bookingDetails->unit_price = unit_price[0];
...
$bookingDetails->save();
and then the same thing with [1] and [2] and so on.
但我如何以这种方式迭代这个?
问候约翰
答案 0 :(得分:1)
只需将for
或foreach
循环设为
for($i=0;$i<count($items['units']);$i++){
$bookingDetails->units = $items['units'][$i];
$bookingDetails->article_group = $items['article_group'][$i];
$bookingDetails->article = $items['article'][$i];
$bookingDetails->description_en = $items['description_en'][$i];
$bookingDetails->unit_price = $items['unit_price'][$i];
$bookingDetails->save();
}
答案 1 :(得分:1)
您可以在 ONE HIT 中使用计数次,而不是按数据 n 次数,计数次数批量插入。
$your_data = array(
array('col_name_1'=>'Value 1', 'col_name_2'=>'Value 2'),
array('col_name_1'=>'Value 3', 'col_name_2'=>'Value 4')
);
your_model_name::insert($your_data);
这将改善您的应用的响应时间。