2011-06-08 77 views
2

我有一個結構化的這樣一個數組:多維陣列上使用的preg_match返回鍵值陣列

$data = array(
    "abc"=>array(
      "label" => "abc", 
      "value" => "def", 
      "type" => "ghi", 
      "desc" => "jkl", 
      ), 
    "def"=>array(
      "label" => "mno", 
      "value" => "qrs", 
      "type" => "tuv", 
      "desc" => "wxyz", 
      ), 
    ); 

我想使用的preg_match與foreach循環執行包含在$陣列上的一個搜索數據並返回鍵值對的嵌套數組。

+1

你的問題是什麼?你所描述的可能是你想要更好的解決方案嗎? – aorcsik 2011-06-08 16:07:45

回答

6

像這樣?

<?php 
$data = array(
    "abc"=>array(
      "label" => "abc", 
      "value" => "def", 
      "type" => "ghi", 
      "desc" => "jkl", 
      ), 
    "def"=>array(
      "label" => "mno", 
      "value" => "qrs", 
      "type" => "tuv", 
      "desc" => "wxyz", 
      ), 
    ); 

$matches = array(); 
$pattern = "https://stackoverflow.com/a/i"; //contains an 'a' 
//loop through the data 
foreach($data as $key=>$value){ 
    //loop through each key under data sub array 
    foreach($value as $key2=>$value2){ 
     //check for match. 
     if(preg_match($pattern, $value2)){ 
      //add to matches array. 
      $matches[$key]=$value; 
      //match found, so break from foreach 
      break; 
     } 
    } 
} 
echo '<pre>'.print_r($matches, true).'</pre>'; 
?> 
12

爲Google員工在那裏,這裏的更好的代碼

$data = <as above> 
$pattern = "/whatever/"; 

$matches = array_filter($data, function($a) use($pattern) { 
    return preg_grep($pattern, $a); 
}); 
+1

謝謝,我從來沒有使用過array_filter或preg_grep。 * *咕* * *我現在要(重新)寫一些代碼... – 2011-06-09 14:41:23

0
$c=['abccd','123','12qw']; // where u'll search 
$a = Array('/a/i', '/\d/i', '/\d+\w/i'); // what is 
$b = array_map(function($a,$c){return (preg_match_all($a,$c,$m))? ($m[0][0]) : '';}, $a,$c); 
print_r($b); 
+1

有人敢解釋嗎? – lama12345 2014-02-01 12:22:39

1

如果你正在使用PHP 5.5,2015年觀看了這個問題,這可能是一個比較簡單的回答:

$elements= array_column($array, 1); //Where 1 is the name of the column or the index 
$foundElements = preg_grep("/regex/i", $elements); 
0
preg_grep('/needle/iu', array_column($haystack, "columnName", "keyName")); 

不區分大小寫uni代碼grep在列columnName$haystack