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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭