0

我想检查一个值在多维数组中是否与我放入的“针”有 50% 或更多相同。

我有一个函数可以检查多维数组中的值是否相同:

function in_array_r($needle, $haystack, $strict = true) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
    }

但是,如果给定百分比的值相同,我想返回函数 true。我认为我需要整合以下内容:similar_text($value1, $value2, $percent);

if {$percent > 50) {
  // do something
}
4

1 回答 1

2

我会尽可能避免递归函数

function in_array_r($needle, $haystack, $strict = true) {
    $eq = 0;
    $diff = 0;
    for($i=0,$n=count($haystack); $i<$n; $i++){
        for($j=0,$m=count($haystack[$i]); $j<$m; $j++){
            if (($strict && $haystack[$i][$j] === $needle) || $haystack[$i][$j] == $needle){
                $eq++;
            } else {
                $diff++;
            }
        }
    }
    return $eq/($eq+$diff);
}
于 2012-12-07T00:19:15.250 回答