返回函数中if语句的结果

时间:2013-01-22 10:44:13

标签: php function if-statement

这是我正在处理的代码。

function calculate_cuisine_type() {
    if ($max == $total2) {
        echo $cItalian;
    } elseif ($max == $total3) {
        echo $cFrench;
    } elseif ($max == $total4) {
        echo $cChinese;
    } elseif ($max == $total5) {
        echo $cSpanish;
    } elseif ($max == $total6) {
        echo $cIndian;
    }
}

我想要做的是为不同的食谱计算'美食类型',我的小程序使用谷歌API返回特定食谱标题的'点击数' - 即馄饨 - 然后通过将该数字除以 100 ,通过另一个查询的返回命中来计算'内聚'比率 - 即( Wontons + Chinese = 50 )。如果你抓住我的漂移,那么凝聚力因子将是2。

现在,我可以将其显示和计算得很好,但是当尝试将最终菜肴类型添加到XML文档时会出现问题,这段代码是否必须具有某种功能?为了在这里调用它:(实际的XML添加代码工作正常)

 $ctNode = $xdoc ->createTextNode (*stuff to be added*);

所以,基本上我要问的是有一种方法可以将IF语句的最终输出分配给另一个变量用于其他地方,或者这是否必须通过Function完成,所以当调用该函数时;它返回IF语句的最终结果。

修改 由于https://stackoverflow.com/users/1044644/ivo-pereira

,问题得以解决

最终密码如果有人有兴趣。

$total = array(
                2 => $total2,
                3 => $total3,
                4 => $total4,
                5 => $total5,
                6 => $total6
            );

        $max = max(array($total2, $total3, $total4, $total5, $total6));

        echo'The highest cohesion factor is: ' . $max;  

                function calculate_cuisine_type($max,$total) {                                      
                    if ($max == $total[2]) {
                        $type = 'Italian';
                    } elseif ($max == $total[3]) {
                        $type = 'French';
                    } elseif ($max == $total[4]) {
                        $type = 'Chinese';
                    } elseif ($max == $total[5]) {
                        $type = 'Spanish';
                    } elseif ($max == $total[6]) {
                        $type = 'Indian';
                    }
                    return $type;
                    }

                    $type = calculate_cuisine_type($max,$total);

1 个答案:

答案 0 :(得分:1)

这可以帮助您在实际情况视图中更好地组织代码:

<?php
$total = array(
    //these numbers are random, just to get the function working. you can change this of course
    2 => 0,
    3 => 3,
    4 => 7,
    5 => 10,
    6 => 14
);

$max = 10;

function calculate_cuisine_type($max,$total) {
    if ($max == $total[2]) {
        $type = 'Italian';
    } elseif ($max == $total[3]) {
        $type = 'French';
    } elseif ($max == $total[4]) {
        $type = 'Chinese';
    } elseif ($max == $total[5]) {
        $type = 'Spanish';
    } elseif ($max == $total[6]) {
        $type = 'Indian';
}
    return $type;
}

$type = calculate_cuisine_type($max,$total);
$ctNode = $xdoc ->createTextNode ($type);

?>

尝试在数组中组织这种内容,它会对你有很大帮助!并且不要忘记将您的数据作为参数传递给函数,否则在这种情况下不会读取它们。

相关问题