我正在创建一个存储食谱的网站。我想制作一个食谱缩放器,你可以在其中输入所需的份量,脚本会转换食谱成分以匹配它。我可以很容易地更改数量,但我正在努力找出如何转换单位。现在我知道我可以输入1500个if/then语句,但我正在努力让它简单一点。:)
我在看一个叫Tasty Kitchen的网站。他们通过AJAX将服务发布到此文件(http://tastykitchen.com/recipes/wp-admin/admin-ajax.php),并且该文件返回成分。然后他们将它们显示在页面上。转到http://tastykitchen.com/recipes/breads/plain-bagels/例如。
我真的很感激能得到的任何帮助。
谢谢!
我的建议是在数据库中存储一个服务,然后简单地乘以你想在页面上提供的人数。
因此,如果你的用户选择了他们想为4个人做一顿饭,你就保留一个变量(会话、cookie等)——在本例中称之为$peeps
——当你输出数据时,你会做这样的事情:
Echo "This will make $peeps portions:";
Echo "Ingredients:<br>";
Echo ($peeps*Ingredient1Quantity)." - ".$ingredient1Name."<br>";
Echo ($peeps*Ingredient2Quantity)." - ".$ingredient2Name."<br>";
等等
如果你想让你的网站也从英制转换为公制,你可以用一个简单的函数很容易地完成。
如果您将所有数据以公制存储在数据库中(或Imperial,但类型相同),则可以根据用户的偏好以类似的方式转换数据,从而非常容易地输出数据:
// Assumes a function that converts to Imperial from Metric called convertToImperial()
Echo "This will make $peeps portions:";v
Echo "Ingredients:<br>";
Echo convertToImperial($peeps*Ingredient1Quantity)." - ".$ingredient1Name."<br>";
Echo convertToImperial($peeps*Ingredient2Quantity)." - ".$ingredient2Name."<br>";
编辑:如果数据库中的所有内容都以公制存储,则可以使用一个函数以最佳英制度量值将数据返回给您。
// For example, input is passed as
// $qty=30 (ml)
// $serves is passed as 3 (ie, three people)
// $type is passed as liquid.
function convertToImperial($qty, $serves, $type)
{
// Metric to Imperial will need a $type passed (Liquid, Weight, Other).
// You can use a switch statement to pass between the different types.
switch ($type)
{
case "Liquid":
// Assumes 5ml is a teaspoon
// Assumes 15ml is a tablespoon
// Assumes 250ml is a cup.
$CalMeasure=$qty*$serves; // Now at 90ml.
// Here you can now choose to either pick the best match
// ie, measurement with least remainder/exact measure
// which in this case would be 6 tablespoons
// or
// switch measurement types after a certain quantity is reached.
if ($CalMeasure>125) // Half a cup
{
return (round($CalMeasure/250,2)." cups");
}
elseif ($CalMeasure>15) // tablespoons
{
return (round($CalMeasure/15,2)." Tablespoons");
}
else
{
return (round($CalMeasure/5,2)." Teaspoons");
}
break;
case "Weight":
// Similar approach to Weights, Convert Grams to Pounds and the like.
return $WeightMeasured;
break;
default: // assumes Other (pinches, sprinkles etc
// Similar approach again.
break;
}
@Caleb-Fluffeh的策略就在这里,他将所有东西存储在一种类型的测量中,然后使用一系列函数将它们转换为其他测量。我构建了一个web应用程序https://Gredio.com它可以进行配方缩放等操作,并能够以这种方式生成非常灵活的报告。一个额外的困难是液体测量与重量的关系。大规模的食品生产总是按重量进行的,但小家伙有时会误解这种区别。通过程序进行液体重量转换可能很复杂,因为你需要知道液体重量的变化很大(想想蜂蜜和水…)