Skip to content

Instantly share code, notes, and snippets.

@WenLiangTseng
Created February 10, 2014 14:59
Show Gist options
  • Save WenLiangTseng/8917409 to your computer and use it in GitHub Desktop.
Save WenLiangTseng/8917409 to your computer and use it in GitHub Desktop.
PHP Search sub-array (PHP搜尋子陣列)
<?php
//source: http://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php
function search($array, $key, $value) {
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
// example
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));
print_r(search($arr, 'name', 'cat 1'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment