创建一个重复的其他函数if

时间:2011-01-29 04:55:26

标签: php

问题标题可能无法证明我的问题,因为我不知道该写什么作为标题。

所以,如果我有这样的事情:

if($type=="a"){
    $s.= " AND type= 'List Apart ";
}elseif($type=="b"){
    $s.= " AND type = 'Before CSS3' ";
}elseif($type=="C"){
    $s.= " AND type = 'Tricks' ";
}elseif($type=="D"){
    $s.= " AND type = 'Stackoverflow' ";

.. etc until Z (just for example)

我可以这样做吗?我已经尝试过,但它不起作用。

$arr = array("b"=>"Before CSS3",..."Z"=>"Somethingd"); // it's not just a simple a-z. A is hardcoded because of the if.
    foreach($arr as $r){
        $r.= "}elseif($type=='key($r)'){   //not the syntax cos I kinda forget :p
        $s.= ' AND type = \'value($r)\' "; //same here
    }
    return $r;

更新:对不起,如果我不够清楚,我已经编辑了我的问题。所以它不仅仅是一个简单的a-z循环,它是一个带有键和值的数组。

5 个答案:

答案 0 :(得分:1)

这取决于您的“类型”可以具有的确切值以及它们映射到的内容。对于您的示例,您可以写下:

$s .= " AND type = '" . strtoupper($type) . "' ";

如果需要陈述,则不。但是如果类型与您需要插入SQL查询的类型不同,请尝试创建一个关联数组并使用$type变量将其编入索引:

$types = array(
  'a' => 'A',
  'b' => 'B',
  'c' => 'C',
  'd' => 'D'
);

$s .= " AND type = '" . $types[$type] . "' ";

答案 1 :(得分:0)

对您处理的数据更加明确,因为根据您的示例,您可以执行以下操作:

if(!empty($type)) {
  $s .= "AND type = '$type'"
}

编辑:

或者这可能是你的意图?

if(in_array($type, range('a','z'))) {
  $s .= "AND type = '$type'"
}

答案 2 :(得分:0)

如果类型是小写A-Z并且你需要将标准包括为大写A-z,为什么不尝试类似的东西:

if(!empty($type))
{
    $s .= " AND type= '" . strtoupper($type) . "'";
}

答案 3 :(得分:0)

你可以这样做:

if(strlen($type) == 1 && $type >= 'A' && $type <= 'Z') {
   $s.= " AND type = '$type' ";
}

答案 4 :(得分:0)

$s .= " AND type= '".strtoupper($type)."'";
相关问题