note 112604 added to function.array-search

From: Date: Wed, 03 Jul 2013 16:02:16 +0000
Subject: note 112604 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-195447@lists.php.net to get a copy of this message
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! ---- Server IP: 87.124.126.49 Probable Submitter: 77.86.38.79 ---- Manual Page -- http://php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/112604 Del: integrated -- https://master.php.net/note/delete/112604/integrated Del: useless -- https://master.php.net/note/delete/112604/useless Del: bad code -- https://master.php.net/note/delete/112604/bad+code Del: spam -- https://master.php.net/note/delete/112604/spam Del: non-english -- https://master.php.net/note/delete/112604/non-english Del: in docs -- https://master.php.net/note/delete/112604/in+docs Del: other reasons-- https://master.php.net/note/delete/112604 Reject -- https://master.php.net/note/reject/112604 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195447) next »