2014-11-05 73 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