PHP - 处理这个问题的好方法是什么?

时间:2012-10-04 05:18:23

标签: php logic

好的,假设当用户选择国家时,他们也会添加“联盟”。这些联合会几乎以地区为中心。

让我说我有这样的事情:

function getFedration($country_iso) {
 // 6 federations
 // afc = asian nations
 // caf = african nations
 // cocacaf = north & central america and Caribbean nations
 // conmebol = south america
 // ofc = Oceanian nations
 // uefa = european nations

$afc = array("Japan", "China", "South Korea");
$caf = array("Cameroon", "Chad", "Ivory Coast");
$concacaf = array("United States" , "Canada", "Mexico");
$conmebol = array("Argetina", "Brazil", "Chile");
$ofc = array("Fiji", "New Zealand", "Samoa");
$uefa = array("Spain", "England", "Montenegro");

/*
PSEUDO-code

If $country_iso is in either of six arrays... mark that as the federation...

*/

return $federation;

}

我知道,它说的是一个国家的名字,但是当它归结为它时,它将是JP而不是JapanCN而不是China的国家/地区。等等。

所以,我想知道,这是一个可行的事情还是你认为有更好的方式?

2 个答案:

答案 0 :(得分:1)

如果联盟只能属于一个国家,我会创建一个数组:

$countryToFederationMap = array(
    'Japan' => 'AFC',
    'China' => 'AFC',
    'Cameroon' => 'CAF',
    // ...
);

然后联邦就是:

return $countryToFederationMap[$country];

答案 1 :(得分:1)

如何将所有联盟放入一个数组,以便循环它?使事情变得更容易,如:

function countryToFederation($country_iso) {
    $federations = array(
        "afc" => array("Japan", "China", "South Korea"),
        "caf" => array("Cameroon", "Chad", "Ivory Coast"),
        "concacaf" => array("United States" , "Canada", "Mexico"),
        "conmebol" => array("Argetina", "Brazil", "Chile"),
        "ofc" => array("Fiji", "New Zealand", "Samoa"),
        "uefa" => array("Spain", "England", "Montenegro"),
    );


    foreach($federations as $federation) {
        if(in_array($country_iso, $federation)) {
            return $federation;
        }
    }
}