array_search_recursive()..帮我找到其中多维数组存在价值 [英] array_search_recursive() .. help me find where value exists in multidimensional array
本文介绍了array_search_recursive()..帮我找到其中多维数组存在价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果值被发现或以下功能很好地告诉我,不是在阵列..
the following function nicely tells me if value is found or not in array ..
function array_search_recursive($needle, $haystack) {
foreach ($haystack 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.
如果针头发现该函数将返回true。此外,$索引是索引为找到的值的数组。
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;
}
例如:
$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'
),
);
的索引为试样5是[2] [1] [1]
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;
}
这篇关于array_search_recursive()..帮我找到其中多维数组存在价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文