【发布时间】:2017-05-18 10:03:03
【问题描述】:
所以... 我有这个包含产品信息的 foreach 循环,我想将信息保存到每个循环的单独数组中。
我正在考虑做这样的事情:
$return_array = array();
foreach($items as $item) {
$return_array[] = $item;
}
但是我在这样做时遇到了麻烦,因为我使用的是来自 html 的输入值,我需要在它们发送到数据库之前添加它们。
我的 foreach 是这样的:
foreach($items as $item) {
<table>
<tr>
<td>
<input value="<?= $item->name ?>" name="item<?= $item->id ?>">
</td>
</tr>
... more table tags
<?php foreach($item as $key) { ?>
<input name ="item<?= $item->id ?>_label<?= $key->label ?>
<?php } ?>
... more table tags
<select name="item<?= item->id ?>_status>
//Choose the state the product is in
<option value="damaged">
<option value="good">
</select>
因此,在与表单一起提交后(这是顺便说一句),我得到如下内容:
(取决于产品有多少标签这个数量可以增加)
$array =
['item1'] = 'test';
['item1_label1'] = 123;
['item1_label2'] = 213;
['item1_status'] = 'good';
['item2'] = 'test2';
['item2_label1'] = 112;
['item2_label2'] = 1232;
['item2_label3'] = 132;
['item2_status'] = 'broken';`
现在我想要的是:
$array =
['item1'] = array[ //name of this doesn't matter
['item1'] = 'test'; // name
['item1_label1'] = 123; //label
['item1_label2'] = 213; //label
['item1_status'] = 'good'; //status
],
['item2'] = array[
['item2'] = 'test2'; //name
['item2_label1'] = 112; //label
['item2_label2'] = 1232; //label
['item2_label3'] = 132; //label
['item2_status'] = 'broken' //status
]
];
我想从表单中创建此信息。 (项目数量也可以增加)。
【问题讨论】:
-
看看如何使用表单名作为数组
-
不要使用
name="itemXY"之类的表单字段名称。请改用name="item[XY]"- 这将为您提供$_POST['item']中的数组,您可以简单地使用foreach 循环,而无需预先知道键。您也可以扩展该语法以使用多个键,所以 f.e.name="item[15][status]"
标签: php arrays forms select multidimensional-array