2012-02-25 75 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'); 
相关问题