3 回答

TA貢獻1806條經驗 獲得超5個贊
當然,如果確實是最好的方法,您可以使用 switch 來做到這一點。很長的切換案例列表令人頭疼......
switch($category){
case 'C01': $artist = 'David Bowie'; break;
case 'C02': $artist = 'Radiohead'; break;
case 'C03': $artist = 'Black Angels'; break;
case 'C04': $artist = 'Glenn Fiddich'; break;
case 'C05': $artist = 'Nicolas Jaar'; break;
default:
switch(substr($category,0,1)){
case A: $artist = 'Pink Floyd'; break;
case B: $artist = 'Lou Reed'; break;
case D: $artist = 'Flat Earth Society'; break;
default: echo'somethig is wrong with category!';}}

TA貢獻1828條經驗 獲得超4個贊
嘗試這個 :
$rules = [
'#A(.{2,2})#' => 'Pink Floyd',
'#B(.{2,2})#' => 'Lou Reed',
'C01' => 'David Bowie',
'C02' => 'Radiohead',
'C03' => 'Black Angels',
'C04' => 'Glenn Fiddich',
'C05' => 'Nicolas Jaar',
'#D(.{2,2})#' => 'Flat Earth Society'
];
$category = 'Dxx';
$out = '';
foreach ( $rules as $key => $value )
{
/* special case */
if ( $key[0] === '#' )
{
if ( !preg_match($key, $category) )
continue;
$out = $value;
break;
}
/* Simple key */
if ( $key === $category )
{
$out = $value;
break;
}
}
echo $out."\n";

TA貢獻1780條經驗 獲得超4個贊
我寫了一個函數。這是 withpreg_match但它很短并且可以重復使用。
function preg_switch(string $str, array $rules) {
foreach($rules as $key => $value) {
if(preg_match("/(^$key$)/", $str) > 0)
return $value;
}
return null;
}
你可以這樣使用它:
$artist = preg_switch("Bdd", [
"A.." => "Pink Floyd",
"B.." => "Lou Reed",
"C01" => "David Bowie",
"C02" => "Radiohead",
"C03" => "Black Angels",
"C04" => "Glenn Fiddich",
"C05" => "Nicolas Jaar",
"D.." => "Flat Earth Society",
]);
而不是*你必須使用.
- 3 回答
- 0 關注
- 191 瀏覽
添加回答
舉報