array_search_recursive() .. help me find where value exists in multidimensional array
the following function nicely tells me if value is found or not in array ..
function array_search_recursive($needle, $haystack) {
foreach ($haystac开发者_运维技巧k as $value) {
if (is_array($value) && array_search_recursive($needle, $value)) return true;
else if ($value == $needle) return true;
}
return false;
}
but i want that array index number where the value exits in the array.
I have modified your function by adding a third parameter passed by reference.
The function will return true if the needle found. Also, the $indexes is an array of indexes to the found value.
function array_search_recursive($needle, $haystack, &$indexes=array())
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$indexes[] = $key;
$status = array_search_recursive($needle, $value, $indexes);
if ($status) {
return true;
} else {
$indexes = array();
}
} else if ($value == $needle) {
$indexes[] = $key;
return true;
}
}
return false;
}
Example:
$haystack1 = array(
0 => 'Sample 1',
1 => 'Sample 2',
2 => array(
'Key' => 'Sample 3',
1 => array(
0 => 'Sample 4',
1 => 'Sample 5'
)
),
4 => 'Sample 6',
3 => array(
0 => 'Sample 7'
),
);
The indexes to "Sample 5" are [2][1][1].
if (array_search_recursive('Sample 5', $haystack1, $indexes)) {
/**
* Output
* Array
* (
* [0] => 2
* [1] => 1
* [2] => 1
* )
*/
echo '<pre>';
print_r ($indexes);
echo '</pre>';
die;
}
精彩评论