2016-01-22 97 views
0

如何從php中的數組中獲取匹配值。 例子:從php中的數組中獲取匹配值和密鑰

<?php 
$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here"); 
?> 

從$一個,如果我有像"He""ld""che",如何顯示基於文本得到匹配值和數組中的鍵文本。就像查詢一樣的SQL。

+0

請您詳細說明您正在嘗試做什麼?我不完全確定你想做什麼。 你是否試圖在數組中存在「他」? – uruloke

回答

1

這是簡單的一個班輪。

您可能正在尋找preg_grep()。使用此功能,您可以從給定的陣列中找到可能的REGEX

$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");  
$matches = preg_grep ("/^(.*)He(.*)$/", $a); 
print_r($matches); 
0

可以遍歷數組,檢查每一個值,如果它包含搜索字符串:

 $searchStr = 'He'; 
     $a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here"); 

     foreach($a as $currKey => $currValue){ 
      if (strpos($currValue, $searchStr) !== false) { 
      echo $currKey.' => '. $currValue.' '; 
      } 
     } 
//prints 1 => Hello 4 => Here 
1

你可以爲創造功能,像這樣:

function find_in_list($a, $find) { 
    $result = array(); 
    foreach ($a as $el) { 
     if (strpos($el, $find) !== false) { 
      $result[] = $el; 
     }; 
    } 
    return $result; 
} 

這裏是你如何可以調用它:

print_r (find_in_list(array("Hello","World","Check","Here"), "el")); 

輸出:

Array ([0] => Hello)