note 62810 deleted from function.array-search by cmb
| From: | cmb@php.net | Date: | Sun, 01 Sep 2019 07:59:40 +0000 |
| Subject: | note 62810 deleted from function.array-search by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212080@lists.php.net to get a copy of this message | ||
Note Submitter: congaz at yahoo dot dk
----
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...