在PHP中的多维数组的价值;如何通过key =&GT搜索
有没有快速的方法来获得,其中一个关键值对在一个多维数组中的所有子阵?我不能说数组将有多深。
Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.
简单的例子数组:
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1")
);
当我搜索键=名称和值=1类函数应该返回:
When I search for key=name and value="cat 1" the function should return:
array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>3,name=>"cat 1")
);
我猜的函数必须是递归以获得下到最深层次。
I guess the function has to be recursive to get down to the deepest level.
code:
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));
print_r(search($arr, 'name', 'cat 1'));
输出:
Array
(
[0] => Array
(
[id] => 1
[name] => cat 1
)
[1] => Array
(
[id] => 3
[name] => cat 1
)
)
如果效率是很重要的,你可以写,这样所有的递归调用存储他们的结果在同一临时 $结果
阵列,而不是合并数组在一起,就像这样:
If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results
array rather than merging arrays together, like so:
function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}
function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}
关键还有就是 search_r
采取它的第四个参数通过引用而不是通过值;与号&放大器;
是至关重要的。
The key there is that search_r
takes its fourth parameter by reference rather than by value; the ampersand &
is crucial.
FYI:如果你有PHP的是旧版本,那么你必须指定在通通过引用部分的呼叫到 search_r
而不是在它的声明。也就是说,最后一行变成 search_r($子数组$键,$值,和放大器; $结果)。
FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r
rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results)
.