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

报告相同问题?

悬赏问题

  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?