检查几个字段以执行开关案例

时间:2013-09-09 03:53:52

标签: php loops switch-statement

我有一个代码可以检查几个字段来执行如下代码:

switch($tag1 || $tag2 || $tag3 || $tag4 ||$tag5){
            case "satay":
            $imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
            break;

            case "digitalmarketing":
            $imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
            break;
            case "chillicrab":
            $imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
            break;
            case "chickenrice":
            $imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
            break;
            case "chendol":
            $imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
            break;
            }

但它不起作用。

任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:1)

Switch仅支持一个值。只有IF条件可以包含ORAND条件。

$tags = get the tag value.
    switch($tags){
                case "satay":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
                break;

                case "digitalmarketing":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
                break;
                case "chillicrab":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
                break;
                case "chickenrice":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
                break;
                case "chendol":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
                break;
                }

答案 1 :(得分:0)

以下应该为您解决问题:

<?php

    $tag1='satay';
    $tag2='test2';
    $tag3='digitalmarketing';

    function isItThere($myTag)
    {
        switch($myTag)
        {
            case "satay":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
                echo $imgput;
                break;
            case "digitalmarketing":
                $imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
                echo $imgput;
                break;
            // etc etc
        }
    }


    for($i=1;$i<4;$i++)
    {
        isItThere(${'tag'.$i});
    }

?>

我基本上设置了一个包含switch语句的小函数,并编写了一个简单的循环来测试变量。

正如我在评论中所说,你不能在switch语句中使用多个变量,但是这将为你提供一个很好的干净的解决方法来做同样的事情,而不需要编写很多长语句。

相关问题