如何搜索具有多个搜索条件的多维数组? [英] How to search an multi-dimensional array with multiple search conditions?
问题描述
我想在条件为两个值的多维数组中搜索键.
I want to search a key in a multidimensional array with two values in the condition.
我知道如何使用单个搜索条件搜索多维数组:
I know how to search a multi-dimensional array with a single search condition:
$key = array_search($journee, array_column($data,'journee'));
但不止于此.这是我的阵列设置:
but not more than that. Here is my array setup:
Array
(
[0] => Array
(
[pseudo] => titi
[journee] => 11
[pts] => 3
)
...
[10] => Array
(
[pseudo] => test
[journee] => 10
[pts] => 6
)
[11] => Array
(
[pseudo] => test
[journee] => 11
[pts] => 4
)
)
如果我只将 11
放在 array_search
中,并且对于 array_column
键,则将 journee
返回0.
If I only put 11
in array_search
and for array_column
the key journee
, it will return 0.
我也想在搜索条件中添加 pseudo
(应该在键 journee
和 pseudo
中搜索特定值).
I want to add pseudo
in the search condition too (the keys journee
and pseudo
should be searched for a specific values).
我该怎么做?
推荐答案
使用一个简单的功能是不可能的.
With one simple function it's not possible.
以下是两个的解决方案:
$search = ['pseudo' => 'test', 'journee' => 10];
$keys = array_keys(
array_filter(
$array,
function ($v) use ($search) { return $v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']; }
)
);
$key = $keys[0];
但是,如果您只需要找到一个键,我建议您使用 foreach
& break
,因为您不必遍历所有值数组(使用 array_filter
会发生这种情况)并在找到某些数据后立即停止:
But if you need to find one key only I advise to use foreach
& break
, because you don't have to iterate over all array of values (what will happen with using array_filter
) and stop immediately when certain data is found:
$key = false;
$search = ['pseudo' => 'test', 'journee' => 10];
foreach ($array as $k => $v) {
if ($v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']) {
$key = $k;
// key found - break the loop
break;
}
}
这篇关于如何搜索具有多个搜索条件的多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!