我的建议是在你的数据库中存储一个服务,然后简单地乘以你想在页面上提供多少人。
因此,如果您的用户选择了他们想要为 4 人制作餐点,那么您保留一个变量(会话、cookie 等等)——让我们$peeps
在这个例子中调用它——当你输出数据时,你会这样做:
Echo "This will make $peeps portions:";
Echo "Ingredients:<br>";
Echo ($peeps*Ingredient1Quantity)." - ".$ingredient1Name."<br>";
Echo ($peeps*Ingredient2Quantity)." - ".$ingredient2Name."<br>";
等等。
如果您希望您的网站也从英制转换为公制,您可以使用简单的功能轻松完成。
如果您将所有数据以公制存储在数据库中(或英制,但都是相同的类型),您可以通过根据用户偏好以类似方式将其转换为用户来轻松地输出它:
// 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;
}