2014-11-05 81 views
0

我想搜索到另一个特定的数组。我正在寻找诸如array_intersect()这样的PHP函数,但这并不是我真正需要的。搜索阵列(带浮点数)与给定的错误

这是我的麻烦:我有$array_1 = [5.3,5.0,6.7]和$ array_2 = [5.0, 5.2,6.5,7.5,8.25]。我需要搜索$ array_1数字到近似值$ array_2,它们应该是连续的。

在这个例子中,结果误差应该小于0.5。 因此,我应该有:$array_1$array_2中找到,因为在给定错误的情况下可以在数组2中找到数组1的值。

  • 5.3 - 5.0 = 0.3(< 0.5)
  • 5.0 - 5.2 = 0.2(< 0.5)
  • 6.7 - 6.5 = 0.2(< 0.5)

是否有一个PHP函数将使用给定的eps搜索$ array_1到$ array_2。错误?我无法在google.com上找到它

我希望我的想法和麻烦对于每个人都有帮助。

非常感谢您提前。

+1

没有。没有。你必须自己写一个。 PHP是一个工具箱。不要触及它,并期望把一栋完全建造的房子拉出来。拔出锤子,螺丝刀,锯子等,然后自己盖房子。 – 2014-11-05 21:01:04

+1

@MarcB:说到锤子:http://blog.codinghorror.com/the-php-singularity/ – 2014-11-05 21:08:37

+0

谢谢。我想知道是否有什么可以帮助我。不要重塑自行车。 – 2014-11-05 21:09:29

回答

1

我不知道你的最终目标,但是这个代码可以让你开始:

$array_1 = array (5.3,5.0,6.7);   #search for this 
$array_2 = array (3.0, 4.4, 5.0, 5.2,6.5,7.5,8.25, 5.0, 5.2, 8.2, 5.0, 4.2, 4.1, 5.3,5.0,6.7); #inside this 

$err = 0.5; 

$matchkeys= array(); 

$i = 0; 
$tmp_match = ''; 
foreach ($array_2 as $k => $v) {  #crawl through array_2 

     if (abs($v - $array_1[$i]) < $err) { 
       echo "match at $k for $i \n"; 
       if ($i==0) {$tmp_match = $k;} 
       $i++;   #if array one matches, then check next array 1 against next array 2 
       if ($i == count($array_1)) { #done matching array_1 ? 
         $matchkeys[] = $tmp_match;  //push first index value of compelte match to array 
         $tmp_match = ''; 
         $i = 0; 
       } 
     } 
     else { 
       $tmp_match = ''; 
       $i=0;   #otherwise start over 
     } 
} 

echo "\n\n found complete matches in array_2 at index: \n"; 
print_r($matchkeys); 
+0

谢谢! 昨天晚上我正在考虑类似的事情。但我没有足够的时间。 – 2014-11-06 20:06:24