Created
February 10, 2014 14:59
-
-
Save WenLiangTseng/8917409 to your computer and use it in GitHub Desktop.
PHP Search sub-array (PHP搜尋子陣列)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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