note 109720 added to function.array-search

From: Date: Tue, 14 Aug 2012 12:25:14 +0000
Subject: note 109720 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-190062@lists.php.net to get a copy of this message
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 ) ---- Server IP: 87.106.1.137 Probable Submitter: 46.5.245.35 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/109720 Del: integrated -- https://master.php.net/note/delete/109720/integrated Del: useless -- https://master.php.net/note/delete/109720/useless Del: bad code -- https://master.php.net/note/delete/109720/bad+code Del: spam -- https://master.php.net/note/delete/109720/spam Del: non-english -- https://master.php.net/note/delete/109720/non-english Del: in docs -- https://master.php.net/note/delete/109720/in+docs Del: other reasons-- https://master.php.net/note/delete/109720 Reject -- https://master.php.net/note/reject/109720 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190062) next »