dongwu5801
2017-09-29 16:39
浏览 42
已采纳

使用分层值在Array或MySQL条目中搜索

I have a database with 5000 entries of local area codes to separate the area code from a phone number string. Area Codes could be a part of other Area Codes. For example

0212 Solingen

02129 Haan

The Area Code of Solingen is a Part of the Area Code of Haan.

  1. Question: Should i store all entries in an array or should i search directly in SQL till the final result?
  2. Question: How can i get the entrie with the most found digits while area codes can be double in array / SQL

The Code i use is

The Result is "03491 52023" which is wrong; It should be "034915 2023"

<?php
$area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
$phone = '0349152023';

foreach ($area_codes as $code) {
  if (substr($phone, 0, strlen($code)) == $code) {
    $phone_string = substr($phone, 0, strlen($code))." ".substr($phone, strlen($code));
  }
}

if (!empty($phone_string)) {
    echo $phone_string;
}

else {
    echo "No AreaCode found.";
}
?>

Thanks for your help.

图片转代码服务由CSDN问答提供 功能建议

我有一个包含5000个本地区号代码的数据库,用于将区号与电话号码字符串分开。 区号可以是其他区号的一部分。 例如

0212 Solingen

02129 Haan

Solingen的区号是该地区的一部分 Haan代码。

  1. 问题:我应该将所有条目存储在数组中还是应该直接在SQL中搜索直到最终结果?
  2. 问题:如何获得最多找到数字的entrie,而区号在数组/ SQL中可以加倍

    我使用的代码是

    结果为“03491 52023”,这是错误的; 它应该是“034915 2023”

     &lt;?php 
     $ area_codes = array('0350','034','034915','03491','0348  ','0349','03491','034916','034917',); 
     $ phone ='0349152023'; 
     
    foreach($ area_codes as $ code){
     if(substr($ phone,  0,strlen($ code))== $ code){
     $ phone_string = substr($ phone,0,strlen($ code))。“”。sububtr($ phone,strlen($ code)); 
      } 
    } 
     
    if(!empty($ phone_string)){
     echo $ phone_string; 
    } 
     
    else {
     echo“No AreaCode found。”; 
    } 
    ?&gt; \  n   
     
     

    感谢您的帮助。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanji1610 2017-09-29 16:45
    已采纳

    You just need to sort array and you will get desired output:

    Working Demo: https://eval.in/871329

    $area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
    sort($area_codes);
    
    $phone = '0349152023';
    
    foreach ($area_codes as $code) {
        $subString = substr($phone, 0, strlen($code)); // stored in var so no need to re-code for substr
        if ($subString == $code) {
            $phone_string = $subString." ".substr($phone, strlen($code));
        }
    }
    
    if (!empty($phone_string)) {
        echo $phone_string;
    }
    
    else {
        echo "No AreaCode found.";
    }
    

    Output:

    034915 2023
    
    点赞 评论

相关推荐 更多相似问题