douzhen9428 2012-02-15 17:40
浏览 244
已采纳

获取php中两个数组的相似度百分比

I need to take two arrays and come up with a percent of similarity. ie:

array( 0=>'1' , 1=>'2' , 2=>'6' , 3=>array(0=>1))

vers

array( 0=>'1' , 1=>'45' , 2=>'6' , 3=>array(0=>1))

Where I would think that the % is 75

or

array( 0=>'1' , 1=>'2' , 2=>'6' , 3=>array(0=>'1'))

vers

array( 0=>'1' , 1=>'2' , 2=>'6' , 3=>array(0=>'55'))

Not sure how to approach this.. just need to end up with a workable float percent. Thank you .

  • 写回答

6条回答 默认 最新

  • drgd73844 2012-02-15 17:50
    关注

    Assuming both arrays are the same length, you can iterate through and see which values are the same for the keys, for example:

    <?php
    $a = array(1,2,3,4);
    $b = array(1,2,4,4);
    $c = 0;
    foreach ($a as $k=>$v) {
        if ($v == $b[$k]) $c++;
    }
    echo ($c/count($a))*100;
    // outputs 75
    ?>
    

    Or just checking whether they contain similar items using in_array.

    <?php
    $a = array(1,2,3);
    $b = array(1,2,4);
    $c = 0;
    foreach ($a as $i) {
        if (in_array($i,$b)) $c++;
    }
    echo ($c/count($a))*100;
    // outputs 66.66...
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理