note 112604 deleted from function.array-search by levim

From: Date: Mon, 24 Feb 2014 22:45:49 +0000
Subject: note 112604 deleted from function.array-search by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198660@lists.php.net to get a copy of this message
Note Submitter: Best Served Cold dot Com ---- Unfortunately a lot of the very well written solutions to the multidimensional array search problem did not work for me, so I wrote this: <?php function recursive_array_key_search ($needle, array $haystack) { foreach(is_array($needle) ? recursive_array_key_search(array_shift($needle), $haystack) : $haystack as $key=>$value) { if((is_array($needle) && reset($needle) === $key) || $needle === $key) { return $value; } if (is_array($value) && $value = recursive_array_key_search($needle, $value)) { return $value; } } } ?> The advantage of this script is that you can specify one or more keys to search on in an array which passes down the array structure. Take this array: Array ( [id] => 709 [type] => post [slug] => derek [url] => http://bestservedcold.com [tags] => Array ( [one] => Array ( [id] => 167 [slug] => bob [title] => Whateverville [description] => [post_count] => 1 ) [two] => Array ( [id] => 168 [slug] => mary [title] => Single [description] => [post_count] => 1 ) ) ) Then using the function you can return either a single variable: <?php recursive_array_key_search('url', $haystack); // returns 'http://bestservedcold.com' recursive_array_key_search('slug', $haystack); // returns the first instance of slug: 'bob' ?> Or, you can specify two or more keys to match in sequence, like so: <?php recursive_array_key_search(array('two', 'slug'), $haystack) // returns 'mary' ?> I hope that's useful to someone!

« previous php.notes (#198660) next »