2012-02-25 73 views
8

我喜歡在數組上執行搜索並在找到匹配項時返回所有值。數組中的鍵[name]就是我正在搜索的內容。當發現匹配時搜索數組並返回所有鍵和值

Array (
[0] => Array 
    (
     [id] => 20120100 
     [link] => www.janedoe.com 
     [name] => Jane Doe 
    ) 
[1] => Array 
    (
     [id] => 20120101 
     [link] => www.johndoe.com 
     [name] => John Doe 
    ) 
) 

如果我做了李四搜索將返回。

Array 
(
    [id] => 20120101 
    [link] => www.johndoe.com 
    [name] => John Doe 
) 

根據我正在搜索的內容重命名數組會更容易嗎?而不是上面的數組,我也可以生成以下內容。

Array (
[Jane Doe] => Array 
    (
     [id] => 20120100 
     [link] => www.janedoe.com 
     [name] => Jane Doe 
    ) 
[John Doe] => Array 
    (
     [id] => 20120101 
     [link] => www.johndoe.com 
     [name] => John Doe 
    ) 
) 
+0

你冒重複鍵的機會,如果你使用的名稱爲你的鑰匙。 – BenOfTheNorth 2012-02-25 00:21:33

+0

比我會忽略第二個想法,並只搜索第一個數組。 – Tim 2012-02-25 00:26:26

回答

6
$filteredArray = 
array_filter($array, function($element) use($searchFor){ 
    return isset($element['name']) && $element['name'] == $searchFor; 
}); 

需要PHP 5.3.x

+0

Short and快速且易於實施。正是我在找什麼。謝謝一堆! – Tim 2012-02-25 00:44:17

1
function search_array($array, $name){ 
    foreach($array as $item){ 
     if (is_array($item) && isset($item['name'])){ 
      if ($item['name'] == $name){ // or other string comparison 
       return $item; 
      } 
     } 
    } 
    return FALSE; // or whatever else you'd like 
} 
+0

已經有一個內置函數'array_search',http://docs.php.net/array_search - >'致命錯誤:無法重新聲明array_search()' – VolkerK 2012-02-25 00:28:14

+1

我的不好,只是將它命名爲其他東西... – scibuff 2012-02-25 01:17:09

1

我想提供一個可選的變化scibuff的回答(這是極好的)。如果你是不是在找一個精確匹配,但數組內的字符串...

function array_search_x($array, $name){ 
    foreach($array as $item){ 
     if (is_array($item) && isset($item['name'])){ 
      if (strpos($item['name'], $name) !== false) { // changed this line 
       return $item; 
      } 
     } 
    } 
    return FALSE; // or whatever else you'd like 
} 

與調用此...

$pc_ct = array_search_x($your_array_name, 'your_string_here'); 
相關問題