Loovel에서 루프를 사용하여 단일 배열에 데이터 배열을 저장합니다.
-
20-12-2019 - |
문제
I enoent를 사용하여 테이블에 삽입 할 수 있도록 데이터 배열을 하나의 배열에 저장하는 방법을 알아 냈습니다.나는 동적 행을 추가하기 위해 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);
.
나는 또한 여기에서 위의 코드를 얻습니다 : 해결 된 쿼리 빌더 다중 삽입foreach
해결책
키가 열 이름이고 값이 값이며 값이있는 연관 배열을 구성하여 여러 값을 삽입합니다.당신이 제공하는 예제가 꽤 많은 지점이기 때문에 당신이 혼란스러워하는 이유는 분명하지 않습니다.
$inserts = array();
foreach ( $input as $v ) {
$inserts[] = array('name' => $v['name'], 'quantity' => $v['quantity']);
}
DB::table('your_table')->insert($inserts);
. 제휴하지 않습니다 StackOverflow