2017-01-18 63 views
1

我有一個函數,它將遍歷PHP中的一個數組,並且都搜索一個值。PHP搜索數組部分或完全匹配

function checkarrayvalues($term, $arr, $strict = false) { 
foreach ($arr as $item) { 
    if (($strict ? $item === $term : $item == $term) || (is_array($item) && checkarrayvalues($term, $item, $strict))) { 
     return true; 
    } 
} 

因此,我已經爲完整/精確匹配工作。但我也需要測試部分比賽,這是我現在丟失的地方。例如,如果有人在數組內搜索「Dall」和「Dallas」,它也需要返回一個正數。

我在如何做到這一點時錯過了什麼?

陣列的樣子:

[Beau Rivage Resort & Casino] => Array 
      (
       [name] => Beau Rivage Resort & Casino 
       [nid] => 100 
       [alias] => /BeauRivage 
       [guestrooms] => 1740 
       [meetingrooms] => 16 
       [largestmr] => 17000 
       [totalms] => 50000 
       [picture] => /2016-12/Beau-Rivage-Fallen-Oak-Golf-Course_0.jpg 
       [region] => SE 
       [segment] => GC 
       [city] => Biloxi 
       [state] => MS 
       [longstate] => mississippi 
       [address] => 875 Beach Boulevard 
       [zip] => 39530 
       [country] => United States of America 
       [distance] => 21.00 
      ) 

     [Bellagio] => Array 
      (
       [name] => Bellagio 
       [nid] => 103 
       [alias] => /Bellagio 
       [guestrooms] => 3933 
       [meetingrooms] => 50 
       [largestmr] => 45000 
       [totalms] => 200000 
       [picture] => /2016-12/Bellagio-exterior.jpg 
       [region] => SW 
       [segment] => BB 
       [city] => Las Vegas 
       [state] => NV 
       [longstate] => nevada 
       [address] => 3600 Las Vega Boulevard South 
       [zip] => 89109 
       [country] => United States of America 
       [distance] => 10.00 
      ) 
+1

我會給strpos一試 – nfo

+0

錯字 - in_array_r應該是checkarrayvalues – user7355700

+0

是的 - 它遞歸地通過數組來搜索該術語。 – user7355700

回答

0

使用帶有strposstriposcall_user_func功能以下擴展的解決方案:

function checkarrayvalues($term, $arr, $strict = false, $partial = false) { 
    if ($partial) { // whether it should perform a partial match 
     $fn = ($strict) ? "strpos" : "stripos"; 
    } 
    foreach ($arr as $item) { 
     if (is_array($item)) { 
      if (checkarrayvalues($term, $item, $strict, $partial)) 
       return true; 
     } elseif (($partial && call_user_func($fn, $item, $term) !== false) 
       || ($strict ? $item === $term : $item == $term)) { 
      return true; 
     } 
    } 
    return false; 
} 

$arr = [ 
    ['Dallas', 'New York'] 
]; 

var_dump(checkarrayvalues('dall', $arr, true, true)); // false 
var_dump(checkarrayvalues('dall', $arr, false, true)); // true 
var_dump(checkarrayvalues('york', $arr, false, true)); // true 
var_dump(checkarrayvalues('york', $arr, false));  // false