2011-11-01 144 views
0

我有這種情況:如何在PHP中處理字符串?

print_r($test); 
echo '<br>'; 
$and = ''; 
for ($i=0; $i<$count; $i++){ 
    $and.= ' u.room = '.$test[$i]; 
    $and.= ' OR '; 
} 

的結果將是:

Array ([0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6) 

u.room = 1 OR u.room = 3 OR u.room = 4 OR u.room = 5 OR u.room = 6 OR 

我想是刪除最後一個「或」這樣的字符串將成爲:u.room = 1 OR u.room = 3 OR u.room = 4 OR u.room = 5 OR u.room = 6

任何想法?

感謝

回答

1
for ($i=0; $i<$count; $i++){ 
    $and.= ' u.room = '.$test[$i]; 

    if ($i != $count-1) { 
    $and.= ' OR '; 
    } 
} 
+0

成功,得益於 – Patrioticcow

1

使用另一個陣列效果很好,用implode產生最終的字符串:

$clauses = array(); 
foreach($test as $t) { 
    $clauses[] = "u.root = {t[$i]}"; 
} 

$ands = implode(',', $clauses); 

然而,對於你的情況下,如果它是一個場和多個值,你可以去在其他地方:

$in = implode(',', $test); 

$sql = " ... WHERE u.room IN ($in)"; 
+0

確保在'$ test'所有值都正確轉義,以避免SQL注入攻擊,雖然。例如,如果你使用的是MySQL,可以這樣做:'$ test = array_map('mysql_real_escape_string',$ test);' – elazar

1

更簡單(儘管不完全相同,如果$test爲空):

$and = "u.room = " . implode(" OR u.room = ", $test);