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


get the percentage of similarity of two arrays in php

我需要取两个数组,并得出相似度的百分比。即:

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

vers

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

我认为%是75

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

vers

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

不知道该如何处理。。只需要最终得到一个可行的浮动百分比。非常感谢。

以下是我最近如何解决这个问题:

$array1 = array('item1','item2','item3','item4','item5');
$array2 = array('item1','item4','item6','item7','item8','item9','item10');
// returns array containing only items that appear in both arrays
$matches = array_intersect($array1,$array2);
// calculate 'similarity' of array 2 to array 1
// if you want to calculate the inverse, the 'similarity' of array 1
// to array 2, replace $array1 with $array2 below
$a = round(count($matches));
$b = count($array1);
$similarity = $a/$b*100;
echo 'SIMILARITY: ' . $similarity . '%';
// i.e., SIMILARITY: 40%
// (2 of 5 items in array1 have matches in array2 = 40%)

假设两个数组的长度相同,您可以遍历并查看键的哪些值相同,例如:

<?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
?>

或者只是使用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...
?>

将计数设置为零。

遍历数组,检查每对元素是否相等。如果是,则递增计数。

最后,相似性是计数除以数组中元素的总数。

这假设数组的长度相同,键也相同——否则很难定义"相似性"。

您可以首先计算项目总数。然后你需要一个函数来告诉你一个子项是否相同(bool)。

然后一次遍历两个数组,计算相同的匹配项。要得到百分比,请将相同的数字除以之前的总计数,并将结果乘以100。

您需要决定如何处理只存在于一个数组中而不存在于另一个数组的元素。此外,如果你想进入元素内部(如果这些元素也是数组),你可以使is_same($a, $b)函数递归并返回一个浮点值(0-1,而不是0-100),并计算该分数,而不是0 FALSE或1 TRUE。

这里有一个算法。

int count = 0;
for(int i = 0; i < arraySize; i++)
{
  if(array1[i] == array2[i])
  {
    count++;
  }
}
float percent = ((count/arraySize)*100);

count($array)将提供数组中元素的总数。然后,您可以比较数组中的数字,并为所有相同的数字设置一个计数器,然后执行[total number of same number/the count($array)] *100。这应该会给出的百分比