-2

switch如何在 PHP 中返回多个值?

在下面的示例中,我尝试为product1返回category1、category2、category3 ,但语句下方的代码仅返回一个值。switch

switch ($product) {
    case "product1":
        $category = "category1";
        break;
    case "product1":
    case "product2":
        $category = "category2";
        break;
    case "product1":
    case "product2":
    case "product3":
        $category = "category3";
        break;
}

有没有办法添加多个值$category?而且我想用逗号分隔值,以便以后可以将它们用作标签。

4

2 回答 2

3

如果要返回多个值,则应使用数组。

// We're going to store or multiple categories into an array.
$categories = array();
switch ($product) {
    case "product1":
        $categories[] = "category1";
        // This case label doesn't have a break statement, and thus it 'falls through'
        // to the next case label, which is "product2". That code block will also be
        // executed.
    case "product2":
        $categories[] = "category2"
    case "product3":
        $categories[] = "category3";
}

break这个片段在 case 代码块的末尾省略了s,因此它使用switch case fallthrough:如果$product == "product1",则匹配的 case 标签将被执行,但“falls through”到 label product2,它也将被执行,依此类推。

如果$product == "product1", 那么是一个包含和值的$category数组。category1category2category3

然后你可以连接数组中的字符串,用逗号分隔,如下所示:

echo implode(",", $categories);

注意:有时,用例失败是有用的,但请注意,它容易出错。如果你的失败是有意的,那么强烈建议你添加一个注释来通知其他程序员这个失败是故意的。否则,他们可能会认为您不小心忘记了该break声明。

于 2014-06-05T11:40:17.010 回答
1

您可以通过以下方式做到这一点。

$category = array();
switch($product)
{

case "product1":
  $category[] = "category1";

case "product2":
  $category[] = "category2";

case "product3":
  $category[] = "category3";
}
return implode(',',$category);

通过附加字符串并删除 break 语句,您可以检查 switch 中所有可能的情况。

于 2014-06-05T11:37:05.263 回答