Created
February 9, 2014 20:27
-
-
Save katzgrau/8905480 to your computer and use it in GitHub Desktop.
PHP: Search an array of object for nested property values
This file contains hidden or 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 | |
/** | |
* Search an array for nested property values | |
* @param array $array The array you're searching over, perhaps something like | |
* $people = array( | |
* array('name' => 'Bill', 'residence' => array('state' => 'NJ', 'zip' => '07701')), | |
* array('name' => 'Anne', 'residence' => array('state' => 'NJ', 'zip' => '07850')), | |
* array('name' => 'Evan', 'residence' => array('state' => 'NY', 'zip' => '10001')) | |
* ) | |
* @param array $filters An associative array of filters to match, like | |
* $filters = array('residence.state' => 'NJ', 'residence.zip' => '07850') | |
* .. Which would return Anne. | |
* Filters can go any number of properties deep, including arrays or objects | |
* @param mixed $default The value to pass back if no items are found | |
* @return array The search results | |
*/ | |
function searcharray($array, $filters, $default = array()) { | |
$results = array(); | |
foreach($array as $i => $item) { | |
$found = true; | |
foreach($filters as $filter => $value) { | |
$properties = explode('.', $filter); | |
$obj = $item; | |
foreach($properties as $i => $p) { | |
if(count($properties) == ($i + 1) && $obj->{$p} != $value) | |
$found = false; | |
if(count($properties) > ($i + 1)) | |
{ | |
if(is_object($obj)) { | |
if(property_exists($obj, $p)) | |
$obj = $obj->{$p}; | |
else | |
$found = false; | |
} elseif(is_array($obj)) { | |
if(array_key_exists($p, $obj)) | |
$obj = $obj[$p]; | |
else | |
$found = false; | |
} | |
} | |
} | |
} | |
if($found == true) $results[] = $item; | |
$found = false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the snippet! Just a notice; you need to add a closing bracket at the very end.