在 laravel 4 上使用循环将数据数组存储到单个数组中


Store arrays of data into a single array using loop on laravel 4

我一直在弄清楚如何将我的数据数组存储到一个数组中,以便我可以使用 eloquent 将其插入表上。我正在使用javascript来添加动态行。这是 js:

$(function(){
var rowCount = document.getElementById('tblContacts').rows.length - 1 ;
var rowArrayId = rowCount ;
function addRow(){
    $("#tblContacts tbody").append(
        "<tr>"+
        "<td><input type='text' name='product[" + rowArrayId + "][name]' class='form-control'/></td>"+
        "<td><textarea name='product[" + rowArrayId + "][description]' class='form-control' rows='1'></textarea></td>"+
        "<td><input type='text' name='product[" + rowArrayId + "][quantity]' class='form-control'/></td>"+
        "<td><input type='text' name='product[" + rowArrayId + "][price]' class='form-control'/></td>"+
        "<td><button class='btnRemoveRow btn btn-danger'>Remove</button></td>"+
        "</tr>");
    $(".btnRemoveRow").bind("click", removeRow);
rowArrayId = rowArrayId + 1; };

function removeRow(){
    var par = $(this).parent().parent(); //tr
    par.remove();
};
});

这是我的 html 文件

<tr>
<td><input type='text' name='product[0][name]' class="form-control"/></td>
<td><textarea name='product[0][description]' class="form-control" rows="1"></textarea></td>
<td><input type='text' name='product[0][quantity]' class="form-control"/></td>
<td><input type='text' name='product[0][price]' class="form-control"/></td>
<td><button class="btnRemoveRow btn btn-danger">Remove</button></td>
 </tr>
$(".btnRemoveRow").bind("click", removeRow);
$("#btnAddRow").bind("click", addRow);          

当我尝试使用时,在我的控制器中

$input = Input::get('product');
dd($input);

我得到了这些结果:

array (size=3)
0 => 
array (size=4)
  'name' => string 'first product' (length=13)
  'description' => string 'first product description' (length=25)
  'quantity' => string '10' (length=2)
  'price' => string '15' (length=2)
1 => 
array (size=4)
  'name' => string '2nd product ' (length=12)
  'description' => string '2nd product description' (length=23)
  'quantity' => string '20' (length=2)
  'price' => string '20' (length=2)
2 => 
array (size=4)
  'name' => string '3rd product ' (length=12)
  'description' => string '3rd product description' (length=23)
  'quantity' => string '25' (length=2)
  'price' => string '30' (length=2)

我从这里学到了: 从 Laravel 4 输入生成新数组

我的问题是我如何将这些数组放入单个数组中以产生这些代码

$insert = array();
foreach($tab as $key => $value)
{
$insert[] = array(
    'id_reservation' => $reservation_id,
    'produit_id' => $key,
    'quantite' => $value
);
}
DB::table('products')->insert($insert);

我也从这里得到上面的代码:[SOLVED] 流畅的查询生成器多次插入,带有 foreach

通过构造一个关联数组来插入多个值,其中键是列名,值是值。 您为什么感到困惑并不明显,因为您提供的示例几乎是正确的:

$inserts = array();
foreach ( $input as $v ) {
    $inserts[] = array('name' => $v['name'], 'quantity' => $v['quantity']);
}
DB::table('your_table')->insert($inserts);