Skip to content
Advertisement

Is there a way to attach an additional value to a key value pair?

I realise the question is not phrased properly, but I’m not sure how else to describe what I mean. Very new to this, so I apologise for any confusion.

I have an array that looks like this:

Array ( [0] => tomatoes [1] => onions [2] => spinach

I need to somehow attach a numerical value to each value. For example: I want tomatoes to have a value of 20, onions 10, and spinach 50.

Additional info:

I need to iterate over this array and subtract the values from a database that looks like this:

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

I have tried searching for this, but because I don’t know any of the keywords to describe what I’m doing, I may have missed answers that exist on SO. So far, I’m getting the array of veggies as below:

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

I need to attach the numeric value to spinach (in the above example) somehow.

Advertisement

Answer

What you have there, as in the form would work you just would be better off using an text/number input field. Then instead of leaving the topping[] blank, fill it it instead with the name of the topping:

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

When the user types a value in it and clicks submit, the POST will end up being similar to this:

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

Then you can loop over the topping array:

foreach($_POST['topping'] as $topping => $count) {
    // database code subtraction here
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement