有没有办法将附加值附加到键值对?

时间:2019-11-02 01:20:34

标签: php

我知道这个问题的措词不正确,但是我不确定该如何描述我的意思。对此非常陌生,对于给您带来的任何困惑,我深表歉意。

我有一个看起来像这样的数组:

阵列([0] =>西红柿[1] =>洋葱[2] =>菠菜

我需要以某种方式将数字值附加到每个值。例如: 我希望西红柿的价值为20,洋葱的价值为10,菠菜的价值为50。

其他信息:

我需要遍历此数组,并从如下所示的数据库中减去值:

+----+-------------+---------+--------+-------+ | id | name | type | amount | unit | +----+-------------+---------+--------+-------+ | 1 | tomatoes | veggies | 1000 | grams | | 2 | onions | veggies | 1000 | grams | | 3 | spinach | veggies | 1000 | grams |

我尝试搜索此内容,但是由于我不知道任何关键字来描述我在做什么,因此我可能错过了SO上存在的答案。到目前为止,我得到的蔬菜阵列如下:

<label for="toppingCheckbox">Spinach</label>
<input type="checkbox" name="topping[]" id="toppingCheckbox" value="spinach">

我需要以某种方式将数值附加到菠菜上(在上面的示例中)。

1 个答案:

答案 0 :(得分:1)

您所拥有的(如表格中所示)可以正常工作,但最好使用文本/数字输入字段。然后,不要将topping[]留空,而应使用顶部的名称进行填充:

<input type="text" name="topping[spinach]" class="topping" value="">

当用户在其中键入一个值并单击提交时,POST最终将类似于以下内容:

Array
(
    topping[spinach] => {number}
    topping[onions] => {number}
)

然后,您可以遍历topping数组:

foreach($_POST['topping'] as $topping => $count) {
    // database code subtraction here
}