This will make sense with an example:
You've got a recipe site, that tracks 3 datapoints:
- recipe name (salad, chowder, etc.)
- ingredients (tomato, potato, pork, etc.)
- ingredient volume (integers only, to keep our example simple)
On the first page of my Recipe Editor
we have a form to list the required ingredients.
Recipe: salad
REQUIRES
__ tomato
__ lettuce
__ cheese
__ schweddy balls
On the second page, we get a list of all required ingredients and input boxes to enter the required volumes:
Recipe: salad
Ingredient Volume
tomato 2
lettuce 1
cheese 1
(contrived, I know, but bear with me)
Now that second form's list of ingredients and <input ... />
boxes are generated dynamically from the database depending on the recipe chosen for editing.
Each ingredient has a numeric ID, so your volume input would look like:
<input type="text" name="17" value="" /> // how many tomatoes?
Once you SUBMIT
, you need to process the $_POST
array and upload all the ingredients and volumes -- but you (or at least I) don't know in advance what will be in that $_POST
array because each recipe calls for differen开发者_如何学JAVAt ingredients == $_POST[???]
The super-kludge I thought of was putting all the ingredient IDs into a comma-separated string, stick that into a hidden input field, and the explode it during processing and use it as $_POST keys to pull out the values. This certainly works, but it makes me feel all dirty inside.
Is there a better approach to getting input values out of $_POST when you don't know your keys in advance?
The easiest way is to use foreach, since $_POST acts just like any other array:
foreach($_POST as $key => $value)
{
switch($key)
{
case 17:
// ...
}
}
You can also check for the presence of specific keys using isset():
if(isset($_POST['17'])) {
// ...
}
And for the record: there's nothing wrong with comma-separated input fields. The best solution is the one that works. :)
That's not an uncommon issue, and for the recipies the approach looks plausible. But there is an alternative approach, if you would be able to adapt the form generation logic:
<input type="number" name="volume[tomatos]" value="">
Or keep using IDs with name="volume[17]"
or something alike.
Anyway I think this is easy to generate with AJAX/DHTML too, and PHP can deal better with an input array like $_GET["volume"][...]
- which in some cases can also be more reliable than receiving an uncertain ID-list. (You would still need the foreach
certainly.)
<input type="text" name="17" value="" />
Assuming your form method is POST...
foreach($_POST as $key => $value){
echo "We need $value of item $key";
}
Should get you headed in the right direction.
foreach ($_POST as $key => $value){
echo "This recipe includes $value of ingredient $key."
}
To get the list of ingredient IDs, extract it from the $_POST array:
$ingredientIDs = array_keys($_POST);
精彩评论