note 109720 deleted from function.array-search by levim
| From: | levim@php.net | Date: | Mon, 24 Feb 2014 22:48:36 +0000 |
| Subject: | note 109720 deleted from function.array-search by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198669@lists.php.net to get a copy of this message | ||
Note Submitter: pal dot sch at gmx dot de
----
Here is a recursive search for a "key" (not value) in nested array/object.
Returns: array with "values" for the searched "key"
<?php
// recursive search for key in nested array, also search in objects!!
// returns: array with "values" for the searched "key"
function search_nested_arrays($array, $key){
if(is_object($array))
$array = (array)$array;
// search for the key
$result = array();
foreach ($array as $k => $value) {
if(is_array($value) || is_object($value)){
$r = search_nested_arrays($value, $key);
if(!is_null($r))
array_push($result,$r);
}
}
if(array_key_exists($key, $array))
array_push($result,$array[$key]);
if(count($result) > 0){
// resolve nested arrays
$result_plain = array();
foreach ($result as $k => $value) {
if(is_array($value))
$result_plain = array_merge($result_plain,$value);
else
array_push($result_plain,$value);
}
return $result_plain;
}
return NULL;
}
?>
Example:
--------
<?php
$example_array = array("a"=>"A1", "b"=>(object)
array("a"=>"A2", "b"=>"B", "C"));
$result_array = search_nested_arrays($example_array, "a");
?>
Result:
-------
Array ( [0] => A2 [1] => A1 )