我们有变量$country,它可以给出~50个不同的值.
并且可变$id.
我们应该做的是给出一个$id对应于$country值的值,例如:
if ($country = 'USA') { $id = 'usa_type'; }
else if ($country = 'France') { $id = 'france_type'; }
else if ($country = 'German') { $id = 'german_type'; }
else if ($country = 'Spain') { $id = 'spain_type'; }
...
...
...
else if ($country = 'Urugway') { $id = 'urugway_type'; }
else { $id = 'undefined'; }
Run Code Online (Sandbox Code Playgroud)
else if 语句每次都重复,其他数据是典型的.
有没有办法缩短这段代码?
喜欢:
[france]:'france_type;
[england]:'england_type;
...
[else]:'undefined'
Run Code Online (Sandbox Code Playgroud)
谢谢.
你可以只创建$id来自$country:
$id = strtolower($country) . '_type';
Run Code Online (Sandbox Code Playgroud)
如果您首先需要确定有效性$country,将所有国家/地区放入数组中,然后使用in_array以确定是否$country有效:
$countries = array('USA', 'France', 'Germany', 'Spain', 'Uruguay');
if (in_array($country, $countries)) {
$id = strtolower($country) . '_type';
}
Run Code Online (Sandbox Code Playgroud)