如何使用php从手机号码获取国家代码

时间:2014-05-06 07:11:29

标签: php country-codes mobile-country-code

我从数据库中获取手机号码我有更多的1000手机号码,我的数据库看起来像这样

   mobilenumber
   971525478965
   919844005522
   45712345678

我想浏览数据库中的每个号码,并从手机号码中找到countrycode,显示countrycode和国家/地区使用php

例如像这样

 countrycode 971 country UAE
 countrycode 91 country India
 countrycode 45 country Denmark

任何人都有任何建议请指导我如何做。

我试过这样,但想要从数据库中检查多个移动号码

 <?php

$number = "971527139011";

    $countrys = array(

    '1' => 'us',
    '2' => 'uk',
    '3' => 'de',
    '44' => 'fi',
    '123' => 'no',
    '971' =>'uae',
    '91' =>'india',
    '92' =>'pakistan'
    );

    $i = 4;
    $country = "";
    while ($i > 0) {
        if (isset($countrys[substr($number, 0, $i)])) {
            $country = $countrys[substr($number, 0, $i)];
            break;
        } else {
            $i--;
        }
    }
    echo $country;


    ?>

编辑

   <?php


$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '1234fedf';
$dbDatabase = 'smsmobile';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");

$sql = "SELECT destinationaddress FROM reporting";
//print $sql;

$queryRes1 = mysql_query($sql);

while($rows=mysql_fetch_assoc($queryRes1))
{
$destinationaddress[] = $rows['destinationaddress']; 

}



$phones = $destinationaddress;



// get your list of country codes
$ccodes = array(
    '1' => 'us',
    '2' => 'uk',
    '3' => 'de',
    '44' => 'fi',
    '123' => 'no',
    '971' =>'uae',
    '91' =>'india',
    '92' =>'pakistan'
);

krsort( $ccodes );

foreach( $phones as $pn )
{
    foreach( $ccodes as $key=>$value )
    {
        if ( substr( $pn, 0, strlen( $key ) ) == $key )
        {
            // match
            $country[$pn] = $value;
            break;
        }
    }
}

print_r( $country );    
    ?>

1 个答案:

答案 0 :(得分:7)

这样的事情会起作用:

// get your list of numbers from DB
$phones = array( '971527139011', '171527139011' );

// get your list of country codes
$ccodes = array(
    '1' => 'us',
    '2' => 'uk',
    '3' => 'de',
    '44' => 'fi',
    '123' => 'no',
    '971' =>'uae',
    '91' =>'india',
    '92' =>'pakistan'
);

krsort( $ccodes );

foreach( $phones as $pn )
{
    foreach( $ccodes as $key=>$value )
    {
        if ( substr( $pn, 0, strlen( $key ) ) == $key )
        {
            // match
            $country[$pn] = $value;
            break;
        }
    }
}

print_r( $country );

修改

数据非常混乱,我建议你将它存储在不同的列中,但是,如果数据的结构总是相同的,这将从中提取国家/代码:

$data = array( 'country : Denmark prefix:45', 'country : Pakistan prefix:92' );

foreach ( $data as $string )
{
    $_a = explode( ':', $string );
    $_b = explode( ' ', $_a[1] );
    $ccode[$_a[2]] = $_b[1];
}

print_r( $ccode );