note 96486 deleted from function.array-search by levim
| From: | levim@php.net | Date: | Mon, 24 Feb 2014 22:46:20 +0000 |
| Subject: | note 96486 deleted from function.array-search by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198664@lists.php.net to get a copy of this message | ||
Note Submitter: jette at nerdgirl dot dk
----
I use this function to search the value of arrays of any dimension, and return the result with keys
preserved:
<?php
function multiArrayValueSearch($haystack, $needle, &$result, &$aryPath=NULL,
$currentKey='') {
if (is_array($haystack)) {
$count = count($haystack);
$iterator = 0;
foreach($haystack as $location => $straw) {
$iterator++;
$next = ($iterator == $count)?false:true;
if (is_array($straw)) $aryPath[$location] = $location;
multiArrayValueSearch($straw,$needle,$result,$aryPath,$location);
if (!$next) {
unset($aryPath[$currentKey]);
}
}
} else {
$straw = $haystack;
if ($straw == $needle) {
if (!isset($aryPath)) {
$strPath = "\$result[$currentKey] = \$needle;";
} else {
$strPath =
"\$result['".join("']['",$aryPath)."'][$currentKey] =
\$needle;";
}
eval($strPath);
}
}
}
?>
Example:
<?php
$ary['ballon']['red'][1] = 'Love';
$ary['ballon']['red'][2] = 'Valentine';
$ary['ballon']['red'][3] = 'Heart';
$ary['ballon']['green'][1] = 'Summertime';
$ary['ballon']['green'][2] = 'Hope';
$ary['ribbon']['yellow'][2] = 'Welcome';
$ary['ribbon']['red'][3] = 'Love';
$ary['ribbon']['red'][4] = 'Love';
echo "<pre>";
//Just call the function with 3 first parameters set:
// 1) The array to search
// 2) The value to find
// 3) A variable to store the result
multiArrayValueSearch($ary,'Love',$match);
print_r($match);
echo "</pre>";
?>
Output:
Array
(
[ballon] => Array
(
[red] => Array
(
[1] => Love
)
)
[ribbon] => Array
(
[red] => Array
(
[3] => Love
[4] => Love
)
)
)
You can easily adapt it to suit your need of matching, by changing line 16 in the function:
<?php
if ($straw == $needle) {
?>