我有一个用户输入发票行项目的视图。当他们单击提交时,数据将以如下数组发送到我的控制器:
Array
(
[amount] => Array
(
[0] => 130.00
[1] => 50.00
)
[quantity] => Array
(
[0] => 1.00
[1] => 1.00
)
[item] => Array
(
[0] => 3
[1] => 4
)
[work_description] => Array
(
[0] => Programming:
[1] => Design:
)
)
现在我需要遍历每一个,通过模型将其添加到数据库中。不确定我是应该使用foreach
还是构建一个空数组并使用array merge
?
所需的结果将遍历每个数组,并添加到数据库中。所以amount[0]
,quantity[0]
,item[0]
,work_description[0]
,然后是下一组密钥。
//needs to be foreach or build array?
$items = array(
'invoice_id' => $prefix_invoices_id,
'amount' => $this->input->post('amount'),
'quantity' => $this->input->post('quantity'),
'item' => $this->input->post('item'),
'work_description' => $this->input->post('work_description'),
'taxable' => $this->input->post('taxable'),
);
$this->load->model('Invoice_item_model');
$prefix_invoice_lines = $this->Invoice_item_model->add_prefix_invoice_items($items);
我的观点以防万一(用户能够克隆行以添加更多行项目,因此它通常会以数组形式出现):
<tbody>
<tr class="tr_clone" id="inv_line_1">
<td>
<select id="line_item_1" name="item[]" class="invoice_line_item">
<option></option>
<?php
foreach($prefix_line_items as $line_item)
{
?>
<option value="<?php echo $line_item['id']; ?>"><?php echo $line_item['item']; ?></option>
<?php
}
?>
</select>
</td>
<td><input type="text" id="description_1" name="work_description[]" class="description" value="" /></td>
<td><input type="currency" id="amount_1" name="amount[]" class="amount" value="" /></td>
<td><input type="number" id="quantity_1" name="quantity[]" class="quantity" value="" /></td>
<td><input type="currency" id="price_1" name="price[]" class="price" value="" readonly/></td>
<td><a href="#" onclick="return false;" class="add-line-item"><i class="fa fa-plus"></i></a> <a href="#" onclick="return false;" class="remove-line-item"><i class="fa fa-minus"></i></a></td>
</tr>
</tbody>
答案 0 :(得分:1)
$array = array(
'amount' => array(
0 => 130.00,
1 => 50.00
),
'quantity' => array(
0 => 1,
1 => 1
),
'item' => array(
0 => 3,
1 => 4
),
'work_description' => array(
0 => 'Programing: ',
1 => 'Design: '
)
);
$insert = array();
for ($i = 0; $i < count($array['item']); $i++)
{
$insert[$i] = array('amount' => $array['amount'][$i], 'quantity' => $array['quantity'][$i], 'item' => $array['item'][$i], 'work_description' => $array['work_description'][$i]); // $insert is ready for insert_batch
}
//var_dump($insert);
答案 1 :(得分:0)
嗯,我能想到的就是这个组合器:
function add_prefix_invoice_items($items = array) {
$rows = [];
$keys = ['amount', 'quantity', 'item', 'work_description', 'taxable'];
$total_keys = count($keys);
$all = $items[$keys[0]];
for ($i = 0; $i < count($all); $i++) {
$values = [];
for ($j = 0; $j < $total_keys; $j++)
$values[] = $items[$keys[$j]][$i]; // fetch next row
$row = array_combine($keys, $values); // combine key => value pairs
// can insert row ('amount' => nnn, 'quantity' => nnn, ...) into the database now
$id = ...
$rows[$id] = $row
}
return $rows;
}