note 62810 added to function.array-search
| From: | congaz at yahoo dot dk | Date: | Fri, 10 Mar 2006 03:38:11 +0000 |
| Subject: | note 62810 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-105178@lists.php.net to get a copy of this message | ||
Search a multi-dimensional array on keys!
-------------------------------------------
I needed to search dynamically in a multi-dimen array on keys. I came up with this little neat
function. It is so amazingly simple, that I actually didn't think it would work - but it
does...
mixed array_searchMultiOnKeys(array, array);
<?php
function array_searchMultiOnKeys($multiArray, $searchKeysArray) {
// Iterate through searchKeys, making $multiArray smaller and smaller.
foreach ($searchKeysArray as $keySearch) {
$multiArray = $multiArray[$keySearch];
$result = $multiArray;
}
// Check $result.
if (is_array($multiArray)) {
// An array was found at the end of the search. Return true.
$result = true;
}
else if ($result == '') {
// There was nothing found at the end of the search. Return false.
$result = false;
}
return $result;
// End of function,
}
// --- Test array_searchMultiOnKeys ---
$multiArray['webpages']['downloads']['music'] = 1;
$multiArray['webpages']['downloads']['pressmaterial'] = 5;
$multiArray['webpages']['links'] = 7;
array_searchMultiOnKeys($multiArray, array('webpages', 'links')); // returns 7.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads')); // returns
true.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads',
'software')); // returns false.
?>
$multiArray / $searchKeysArray can be any size.
Happy hacking...
----
Server IP: 195.184.96.15
Probable Submitter: 86.52.23.54
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.array-search.php
Edit -- http://master.php.net/note/edit/62810
Del: integrated -- http://master.php.net/note/delete/62810/integrated
Del: useless -- http://master.php.net/note/delete/62810/useless
Del: bad code -- http://master.php.net/note/delete/62810/bad+code
Del: spam -- http://master.php.net/note/delete/62810/spam
Del: non-english -- http://master.php.net/note/delete/62810/non-english
Del: in docs -- http://master.php.net/note/delete/62810/in+docs
Del: other reasons-- http://master.php.net/note/delete/62810
Reject -- http://master.php.net/note/reject/62810
Search -- http://master.php.net/manage/user-notes.php