我正在处理食谱库存清单。用户可以输入多种成分,其中每种成分都有 名称 (番茄,洋葱,牛奶), 金额 (5个西红柿,1个洋葱), 测量 (oz,tbsp,cup)和 分数 (如果需要)( 1/4杯,1/2汤匙,3/4茶匙)。我想将每个变量保存为一个单独的变量,以便我以后可以使用它来创建一个购物清单。
我可以使用foreach函数来完成这项工作吗?对于我可以使用的每种成分,我怎样才能将四个变量设置到一个数组中?
或者有另一种方法吗?一个变量的多值可能吗?
<?php
$recipe = $_POST["recipe"];
$ingredient_amount_01 = $_POST["ingredient_amount_01"];
$fractions_01 = $_POST["fractions_01"];
$measurement_01 = $_POST["measurement_01"];
$ingredient_01 = $_POST["ingredient_01"];
if (!isset($_POST['submit'])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>Recipes</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Recipe Name:<input type="text" size="12" maxlength="12" name="recipe"><br />
Ingredients<br />
1:<select name="ingredient_amount_01">
<option value="">Amount...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option></select>
<select name="fractions_01">
<option value="">---</option>
<option value="one_quarter">¼</option>
<option value="one_half">½</option>
<option value="three_quarters">¾</option></select>
<select name="measurement_01">
<option value="">Measurement...</option>
<option value="cup">Cup</option>
<option value="oz">Oz</option>
<option value="scoop">Scoop</option>
<option value="slice">Slice</option>
<option value="tablespoon">Tbsp</option>
<option value="teaspoon">Tsp</option></select>
<input type="text" size="12" maxlength="100" name="ingredient_01" placeholder="Ingredient"><br />
<input type="submit" value="submit" name="submit">
</form>
<?
} else {
echo "Hello. Here is the recipe for <b>" .$recipe. "</b> that you've submitted.<br />";
echo "Ingredients:<br />";
foreach ($ingredient as $g) {
echo $g <-- This would show something like, 2 1/2 cup milk -->. "<br />";
}
echo "Recipe:".$recipe."<br />";
echo "Item Amount:".$ingredient_amount_01."<br />";
echo "Fractions:".$fractions."<br />";
echo "Measurement:".$measurement."<br />";
echo "Ingredient:".$ingredient."<br />";
}
?>
答案 0 :(得分:3)
您可能希望将字段命名为:
<select name='ingredient[]'> <!--options here --> </select>
<select name='fraction[]'><!-- fraction options here --></select>
etc.
这会在您发布数据时将值加载到数组中,然后您可以使用for循环迭代所有提交的字段。例如,
<?php
$ingredients = $_POST['ingredients']; //creates an array of all posted ingredients
$fractions = $_POST['fractions']; //creates an array of all posted fractions
for ($i = 0; $i < count($ingredients); $i++)
{
$all_ingredients[] = $ingredient[$i] . ' ' . $fractions[$i];
}
?>
假设第一种成分是西红柿而且分数是1/4,回显$ all_ingredients [0]会显示: 番茄1/4 您可以对此进行扩展以包括所有表单域,并输出您想要的字符串。
答案 1 :(得分:0)
改变这个:
$recipe = $_POST["recipe"];
$ingredient_amount_01 = $_POST["ingredient_amount_01"];
$fractions_01 = $_POST["fractions_01"];
$measurement_01 = $_POST["measurement_01"];
$ingredient_01 = $_POST["ingredient_01"];
有了这个:
$ingredient['recipe'] = $_POST["recipe"];
$ingredient['amount_01'] = $_POST["ingredient_amount_01"];
...
在你的foreach中你可以使用:
foreach($ingredient as $key=>$value)
echo $key.":".$value;