我是php的新手,想要探索如何以不同的方式实现同样的目标。我有以下工作代码,并希望看到更好的编码方式。任何建议都表示赞赏。
<?php
$districts = "Aizawl";
$fc = "First City";
$sc = "Second City";
$tc = "Third City";
if ($districts == "Aizawl") {
$city = $fc;
} elseif ($districts == "Lunglei") {
$city = $sc;
} elseif ($districts == "Saiha") {
$city = $tc;
}
?>
<?php
echo $city;
?>
答案 0 :(得分:3)
<?php
$districts = "Aizawl";
$districts_city = array(
'Aizawl' => 'First City',
'Lunglei' => 'Second City',
'Saiha' => 'Third City',
);
$city = $districts_city[$districts];
echo $city;
答案 1 :(得分:2)
$districts = 'Aizawl';
$map = array(
'Aizawl' => 'First city',
'Lunglei' => 'Second city',
'Saiha' => 'Third city',
);
if (isset($map[$districts])) {
$city = $map[$districts];
} else {
// show error...
}
答案 2 :(得分:2)
使用关联列表或哈希表。
$array = array(
"Aizwal" => "First City",
"foo" => "2nd",
"bar" => "3rd",
);
$city=$array[$districts]
答案 3 :(得分:0)
Bellow code我会很乐意
<?php
$i=2;
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
答案 4 :(得分:-1)
使用开关声明
switch ($districts) {
case "Aizawl":
$city=$fc;
break;
case "Lunglei":
$city=$sc;
break;
case "Saiha":
$city=$tc;
break;
}
答案 5 :(得分:-1)
使用switch
statement。另外,如果你没有在其他地方使用$fc
,$sc
和$tc
变量,我只需将$city
变量设置为{{1}内的字符串内容声明。
switch