2011-01-29 39 views
1

問題標題可能不能證明我的問題的功能,因爲在所有我不知道寫什麼作爲標題。創建重複否則,如果

所以,如果我有這樣的事情:

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環,它與鍵和值的數組。

回答

0

一點更加明確與您一起上的數據,因爲根據你的榜樣,你可以簡單地做:

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

編輯:

或者,也許這是你的意圖是什麼?

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

如果類型是要去較低的情況下,AZ,你需要包括的標準爲大寫了Az爲什麼不嘗試這樣的:

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

這取決於什麼確切看重你的「類型」可以有,他們映射到什麼。對於你的例子,你可以寫這個:

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

沒有,如果需要聲明。但是,如果類型是從你需要插入到您的SQL查詢的類型不同,儘量使關聯數組和索引到它與您$type變量:

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

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

你可以這樣做:

if(strlen($type) == 1 && $type >= 'A' && $type <= 'Z') { 
    $s.= " AND type = '$type' "; 
} 
0
$s .= " AND type= '".strtoupper($type)."'"; 
相關問題