note 96486 added to function.array-search
| From: | jette at nerdgirl dot dk | Date: | Mon, 01 Mar 2010 16:07:32 +0000 |
| Subject: | note 96486 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166512@lists.php.net to get a copy of this message | ||
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) {
?>
----
Server IP: 69.147.83.197
Probable Submitter: 80.167.136.250
----
Manual Page -- http://www.php.net/manual/en/function.array-search.php
Edit -- https://master.php.net/note/edit/96486
Del: integrated -- https://master.php.net/note/delete/96486/integrated
Del: useless -- https://master.php.net/note/delete/96486/useless
Del: bad code -- https://master.php.net/note/delete/96486/bad+code
Del: spam -- https://master.php.net/note/delete/96486/spam
Del: non-english -- https://master.php.net/note/delete/96486/non-english
Del: in docs -- https://master.php.net/note/delete/96486/in+docs
Del: other reasons-- https://master.php.net/note/delete/96486
Reject -- https://master.php.net/note/reject/96486
Search -- https://master.php.net/manage/user-notes.php