如何使用IF-ELSE比较php中的数据

如何使用IF-ELSE比较php中的数据,php,html,Php,Html,我有一个变量let,它表示$components,其中包含 面粉、糖、起酥油、植物油脂、鸡蛋、玉米淀粉、蛋糕OMath、葡萄糖、 乳清粉、可可粉、乳糖、全脂奶粉、盐、脱脂奶粉、 糊精、咖啡粉、黄油、脱脂炼乳、蛋黄粉、 发酵剂、着色剂(焦糖、红木和胡萝卜素)、乳化剂(大豆来源)、香料 现在我想把它的$component 如果$Components含有乳化剂和起酥油,它将显示(echo)“好产品” 但是,如果没有乳化剂和起酥油,则为“最佳产品”(否则为“最佳产品” 如何在php中编写此代码 非常感谢

我有一个变量let,它表示
$components
,其中包含

面粉、糖、起酥油、植物油脂、鸡蛋、玉米淀粉、蛋糕OMath、葡萄糖、

乳清粉、可可粉、乳糖、全脂奶粉、盐、脱脂奶粉、

糊精、咖啡粉、黄油、脱脂炼乳、蛋黄粉、

发酵剂、着色剂(焦糖、红木和胡萝卜素)、乳化剂(大豆来源)、香料

现在我想把它的
$component

  • 如果$Components含有乳化剂和起酥油,它将显示
    (echo)
    “好产品”

  • 但是,如果没有乳化剂和起酥油,则为“最佳产品”(否则为“最佳产品”

  • 如何在php中编写此代码

    非常感谢

    用于检查项目是否在数组中

    $ingredients = array('First ingredient', 'Second ingredient');
    
    如果成分是由逗号分隔的字符串,则可以使用以下命令将其转换为数组:

    $ingredients = explode(',',$ingredients);
    
    您可能需要修剪每个项目,以确保删除每个项目周围的任何空白(这将打乱您的in_array()检查:

    最后,您可以进行检查:

    if(in_array('First ingredient',$ingredients))
    {
        // First ingredient is in the array
    }
    
    要检查数组是否同时包含这两个元素,请执行以下操作:

    if(in_array('First ingredient',$ingredients) AND in_array('Second ingredient',$ingredients))
    {
        // First and second ingredient is in the array
    }
    
    要检查它是否包含一个或另一个:

    if(in_array('First ingredient',$ingredients) || in_array('Second ingredient',$ingredients))
    {
        // First or second ingredient is in the array
    }
    

    您可以根据需要添加任意数量的“和”和“和”。

    如果您的配料是连续的:

    if ( strpos($ingredients, "emulsifier") === false
      && strpos($ingredients, "shortening") === false ) {
       echo 'Best Product';
    } elseif ( strpos($ingredients, "emulsifier") !== false
      && strpos($ingredients, "shortening") !== false ) {
       echo 'Good Product';
    }
    

    $Components
    是数组还是字符串?非常感谢。这是真的。如果我想添加比较,strign不止一个。例如,如果$Components包含第一种成分、第二种成分或第三种成分,这就是好产品。非常感谢您可以创建数组:$good_elements、$bad_elements和d使用数组_intersect()。很抱歉,我仍然有一个问题。如何将所有成分转换为数组?因为我得到的字符串为{面粉、糖、起酥油、植物脂肪和油、鸡蛋、玉米淀粉、蛋糕油、葡萄糖、乳清粉、可可粉、乳糖、全脂奶粉、盐、脱脂奶粉、糊精、咖啡粉、黄油、加糖脱脂炼乳、蛋黄粉、发酵剂、着色剂(焦糖、红木和胡萝卜素)、乳化剂(大豆来源),香水}在名为$Components的单个字符串中。Thanksse更新了答案,只要字符串中的所有成分都用逗号分隔,就可以使用。如果这些花括号位于字符串的开头和结尾,则需要将它们去掉。否则,第一个和最后一个元素也将包含括号。如果要检查multiple如果(!count(array_diff(array_intersect($contracents,$good),$good)),您可以使用:if(!count(array_diff(array_intersect($contracents,$good)))检查所有好的配料是否都在数组中。
    if ( strpos($ingredients, "emulsifier") === false
      && strpos($ingredients, "shortening") === false ) {
       echo 'Best Product';
    } elseif ( strpos($ingredients, "emulsifier") !== false
      && strpos($ingredients, "shortening") !== false ) {
       echo 'Good Product';
    }