[英]PHP foreach() outputs only the last item of an array
作為我上一篇文章的續集,我的目的只是讓我的問題直截了當且簡短,但顯然,為了清楚起見,最好包括所有涉及的模塊。
我正在開發一個 CodeIgniter 項目,該項目要求用戶在輸入后數組的幫助下提供多個選項,如下圖所示:
<form action="javascript:void(0)" id="add_stock">
<div class="stock">
<div>
<div class="form-group col-md-4">
<input type="text" name="item[]" placeholder="Name of item" class="form-control item" id="item" />
<span class="item_err"></span>
</div>
<div class="form-group col-md-4">
<input type="text" name="unit[]" list="units" placeholder="Enter unit of measurement" class="form-control unit" id="unit" />
<datalist id="units">
<option>cube</option>
<option>cup</option>
</datalist>
<span class="unit_err"></span>
</div>
<div class="form-group col-md-3">
<input type="text" onfocus="(this.type='number')" name="quantity[]" placeholder="Enter quantity" class="form-control quantity" id="quantity" />
<span class="quantity_err"></span>
</div>
<div class="form-group col-md-1">
<button class="btn btn-primary add-more-stock" title="Add more item" style ="height:33px;margin-top: ;"><i class="fa fa-plus"></i></button>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
<div class="form-group msg"></div>
<div class="form-group col-md-12">
<button class="btn btn-primary add-stock text-uppercase"><i class="fa fa-plus"></i> add stock</button>
</div>
</form>
我有一個 jQuery 代碼,它附加了額外的輸入字段,如下所示:
var max_fields = 20; // maximun inputs allowed
var items = $('.stock');
var x = 1;
$('.add-more-stock').click(function (e) {
e.preventDefault();
if (x < max_fields) {
x++;
$('.stock').append('<div><div class="form-group col-md-4"><input type="text" name="item[]" placeholder="Name of item" class="form-control item" id="item" /><span class="item_err"></span></div><div class="form-group col-md-4"><input type="text" name="unit[]" list="units" placeholder="Enter unit of measurement" class="form-control unit" id="unit" /><datalist id="units"><option>cube</option><option>cup</option><option>mudu</option><option>bags</option><option>carton</option> <option>crate</option> <option>bottle</option></datalist><span class="unit_err"></span></div><div class="form-group col-md-3"><input type="text" name="quantity[]" placeholder="Enter quantity" class="form-control quantity" id="quantity" /> <span class="quantity_err"></span></div><button class="btn btn-danger remove-stock col-sm-1" title="Remove item" style ="height:33px;margin-bottom: -1px; width: 40px;"><i class="fa fa-trash"></i></button></div>');
}else{
$('.input-alert').attr('class','alert alert-warning').html('<i class="fa fa-info-circle"></i> You have reached the maximun of 20 input fields reached.').show();
}
})
$(items).on('click','.remove-stock',function (e) {
e.preventDefault();
$(this).parent('div').remove();
$('.input-alert').hide();
})
這是完整的 jQuery 代碼,它將文本字段的內容傳遞給我的 controller:
$('.add-stock').click(function (e) {
var item = new Array();
var unit = new Array();
var quantity = new Array();
var item_arr = $("input[name^='item']");
var unit_arr = $("input[name^='unit']");
var quantity_arr = $("input[name^='quantity']");
item_arr.each(function(){
item.push(this.value);
});
unit_arr.each(function(){
unit.push(this.value);
});
quantity_arr.each(function(){
quantity.push(this.value);
});
$.ajax({
url: '<?php echo base_url()?>admin/add_stock',
type: 'post',
data: {item:item,unit:unit,quantity:quantity},
dataType: 'json',
beforeSend: function () {
$(".add-stock").html("<img src='<?php echo base_url()?>asset/images/a.gif' width='20' height='20'/> proceesing...");
},
success: function (data) {
if (data.success) {
$('.add-stock').html('<i class="fa fa-plus"></> add stock');
$('.msg').attr('class', 'alert alert-success').html('<i class="fa fa-check"></> '+data.msg).delay(5000).fadeOut();
}else if (data.error) {
if (data.unit) {
$('.add-stock').html('<i class="fa fa-plus"></> add stock');
$('.unit_err').attr('class', 'text-danger').html(data.unit).delay(5000).fadeOut();
}else if (data.item) {
$('.add-stock').html('<i class="fa fa-plus"></> add stock');
$('.item_err').attr('class', 'text-danger').html(data.item).delay(5000).fadeOut();
}else if (data.quantity) {
$('.add-stock').html('<i class="fa fa-plus"></> add stock');
$('.quantity_err').attr('class', 'text-danger').html(data.quantity).delay(5000).fadeOut();
}else if (data.failed) {
$('.add-stock').html('<i class="fa fa-plus"></> add stock');
$('.msg').attr('class', 'alert alert-danger').html('<i class="fa fa-times"></> could not procees request...').delay(5000).fadeOut();
}
}
},
error: function () {
$('add-stock').html('<i class="fa fa-plus"></> add stock');
$('.msg').attr('class', 'alert alert-warning').html('<i class="fa fa-warning"></> something went wrong.').delay(5000).fadeOut();
}
})
})
因此,我試圖在 PHP(CodeIgniter)的幫助下獲取選項,以便將它們存儲在單獨的行和相應的列中......
到目前為止,這是我完整的 controller
function add_stock()
{
$items = $_POST['item'];
$units = $_POST['unit'];
$quantitys = $_POST['quantity'];
foreach ($items as $item) {
$stock['item'] = $item;
}
foreach ($units as $unit) {
$stock['unit_of_measurement'] = $unit;
}
foreach ($quantitys as $quantity) {
$stock['quantity'] = $quantity;
}
$stock['added_by'] = 'Admin';
$stmt = $this->db->insert('stocks', $stock);
if($stmt):
$array = array('success' => true, 'msg'=>'Item has been successfully added to store');
else:
$array = array('error' => true, 'failed'=>true);
endif;
echo json_encode($array);
}
現在,問題在於,不是顯示數組的全部內容,而是只輸出最后一個內容,即如果 $array 的內容是 ['a','b'],而不是顯示 a,b foreach () 循環只顯示 b。
但是當我回顯 $items、$units 或 $quantitys 本身時,會顯示數組的內容。
那么,請問如何獲取數組的所有內容並將它們插入不同的行?
謝謝!
您的問題從您的表單開始,然后在您的 controller 中變得更糟。
您的 controller 中的具體問題是這樣的:
foreach ($items as $item) {
$stock['item'] = $item;
}
您正在迭代$items
數組,但在每次迭代時覆蓋$stock['item']
的值。 僅存儲最后一個值。
要解決此問題,您需要做很多事情:
首先,在表單名稱中使用數組索引。 這允許您提取在$_POST
中收到的 arrays 中的相應值
在您的 HTML 中,在您的<input>
字段中使用name="item[0]"
, name="unit[0]"
, name="quantity[0]"
。
然后,在添加新行的 Javascript 代碼中,為每個新行增加索引。 您已經有一個可以用於 this = x
的計數器。
'<input type="text" name="item[' + x + ']" placeholder="Name of item" class="form-control item" id="item" />'
(我沒有復制整行 - 你明白了)
這些更改應該在您的輸入中為您提供三個 arrays ,您可以在單個循環中進行迭代:
$items = $_POST['item'];
$units = $_POST['unit'];
$qtys = $_POST['quantity'];
for($i=0;$i<count($items); $i++) {
$item = $items[$i];
$unit = $units[$i];
$qty = $qtys[$i];
// Do your database update here with these three variables
}
純粹主義者會注意到您可以直接使用數組元素。 我同意,但這更清楚。
您可以擴展索引以提供二維數組:
name="products[0]['item']"
name="products[0]['unit']"
name="products[0]['quantity']"
(以及在 Javascript 中使用x
的相應更改)
然后遍歷 $_POST]['products']:
foreach($_POST['products'] as $product) {
$unit = $product['unit'];
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.