Search array and return all keys and values when match found

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I like to perform a search on an array and return all values when a match is found. The key [name] in the array is what I am doing a search on.

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

If I did a search for John Doe it would return.

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

Would it be easier to rename the arrays based on what I am searching for. Instead of the above array I can also generate the following.

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     ) )

回答1:

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

Requires PHP 5.3.x



回答2:

I would like to offer an optional change to scibuff's answer(which was excellent). If you are not looking for an exact match, but a string inside the array...

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 }

Call this with...

$pc_ct = array_search_x($your_array_name, 'your_string_here');


回答3:

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 }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!