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.

  • 写回答

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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器