在您的代码中,您始终将$countrys中的第一个国家/地区分配给$country。所以你总是会以我们结束。
您应该从您的电话号码中获取前3个,2个或1个数字,然后检查是否array key exists,而不是这样做。如果是,则将其用作数组的查找索引。
这是一个伪代码,供您开始使用:
perform a loop to get the first 3, 2, and 1 digit(s) from the phone number:
// Order is important as you want to match '123' before you match '1'
Check if the array key for the digit exists in the $countrys
If yes, get the country name and quit the loop
If not, go to the next less digit
If the key is found:
Print the country name
Else:
Print the country is not found
以下是您如何为3位数执行此操作的部分代码。您只需添加循环(例如for-loop)即可简化您的工作。
$number = "123777777";
// Add your loop here to check for 3, 2, 1 digit
$we = substr($number, 0, 3);
$countrys = array(
'1' => 'us',
'2' => 'uk',
'3' => 'de',
'44' => 'fi',
'123' => 'no'
);
$array = "$we"; // You don't need this
if (array_key_exists ($we, $countrys))
{
// Remember to break out of your loop when the country is found
$country = $countrys[$we];
}
else
{
$country = "Non in list";
}
// End your loop here
echo "${we} is ${country}\n";