dongqiang8683 2016-08-28 12:04
浏览 121
已采纳

使用字符串比较函数比较另一个数组中的值是否存在于另一个数组中

I have 2 comma separated values, which I convert in 2 arrays, named: $companyCad and $programCad

Those 2 arrays return values in the following format:

$companyCad

Array
(
    [0] => 52.10
    [1] => 62
    [2] => 64.15.44.25
    [3] => 65.10
    [4] => 65.14
    [5] => 65.21
    [6] => 70
    [7] => 71
    [8] => 71.15.12
    [9] => 93.55
)

$programCad

Array
(
    [0] => 92.55
    [1] => 92.74
    [2] => 93
    [3] => 94.10
    [4] => 98.12
    [5] => 98.66
)

To compare if any of the $companyCad values exist in the $programCad I use the following code:

if (array_intersect($companyCad, $programCad)) {
    echo "Found";
} else {
   echo "Not found";
}

Above code return not found since 93.55 from $programCad is not found in the array $companyCad. I know that the code works just fine.

However I need partial match, that is:

If the value of the $companyCad is longer than value of the $programCad for example $companyCad[9] = 93.55 and the $programCad[2] = 93 that should be considered as match.

If the $companyCad[9] = 93.55 and the $programCad[2] = 93.1 it should not be considered as match however.

If the $companyCad[9] = 93.5X and the $programCad[2] = 93.5 it should be considered as match also. (X = any number)

Here are some more explanations of eventual format of the array values:

Array value will have at least 2 digits = XX The shortest value may be XX while the longest is XX.XX.XX.XX However it may end with 1 digit in some cases, example XX.X or XX.XX.X for example.

Any idea how can I do this partial match?

  • 写回答

4条回答 默认 最新

  • doudeng3008 2016-08-28 12:34
    关注

    One way to accomplish it is using nested loops and strpos to look if the haystack (value from first loop) starts with the needle (value from second loop).

    $companyCad = array("52.10", "62", "64.15.44.25", "65.10", "65.14", "65.21", "70", "71", "71.15.12", "93.55");
    $programCad = array("92.55", "92.74", "93", "94.10", "98.12", "98.66", "71.1");
    
    $found = false;
    foreach($companyCad as $comp) {
        foreach($programCad as $prog) {
            if(strpos($comp, $prog) === 0) {
                $found = true;
                break;
            }
        }
    }
    
    if($found === true) {
        echo "Found";
    } else {
        echo "Not Found";
    }
    

    Live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题