0

我可以以某种方式简化下面的代码并仅使用一个 switch 语句吗?看起来我需要第三个开关,所以如果可能的话,最好只使用一个。

    $input_separator= $_REQUEST['input_separator'];

    switch ($input_separator) {  
        case "new_line":
            $input_separator="\n";
            break;
        case "comma":
            $input_separator=",";
            break;
        case "none":
            $input_separator="";
            break;
    }



    $output_separator= $_REQUEST['output_separator'];

    switch ($output_separator) {
        case "new_line":
            $output_separator="\n";
            break;
        case "comma":
            $output_separator=",";
            break;
        case "none":
            $output_separator="";
            break;
    }
4

2 回答 2

2

看起来您不需要任何 switch陈述:

$input_separator = $_REQUEST['input_separator'] == "new_line" ? "\n" : "";
$output_separator = $_REQUEST['output_separator'] == "new_line" ? "\n" : "";

编辑:试试这个:

$separators = Array(
    "new_line"=>"\n",
    "comma"=>",",
    "none"=>""
);
$input_separator = $separators[$_REQUEST['input_separator']];
$output_separator = $separators[$_REQUEST['output_separator']];
于 2013-04-28T01:24:03.987 回答
1

你为什么不使用简单的功能?

function convert_seperator($seperator){
    $ret = '';
    switch ($seperator) {  
        case "new_line":
            $ret = "\n"; // or $ret = PHP_EOL;
            break;
        case "comma":
            $ret = ",";
            break;
        case "none":
            $ret = "";
            break;
        default:
            exit('Invalid seperator');
    }
    return $ret;
}
$input_separator = convert_seperator($_REQUEST['input_separator']);
$output_separator = convert_seperator($_REQUEST['output_separator']);
于 2013-04-28T01:37:26.147 回答