如何在PHP中一次通过多个值搜索多维数组?
给出以下2D数组:
$data_info_array = array(
array(
'score' => '100',
'name' => 'Alice',
'subject' => 'Data Structures'
),
array(
'score' => '50',
'name' => 'Bob',
'subject' => 'Advanced Algorithms'
),
array(
'score' => '75',
'name' => 'Charlie',
'subject' => 'Distributed Computing'
)
);
// this gets the key when I search for the score of 50 from one column
$index = array_search('50', array_column($data_info_array, 'score'));
echo $index;
如果要按两个值搜索,我只能想到:
If I want to search by two values I can only think of something like:
$index1 = array_search('50', array_column($data_info_array, 'score'));
$index2 = array_search('Bob', array_column($data_info_array, 'name'));
$real_index = ( $index1 === $index2 ) ? $index1 : null;
有没有一种方法可以一起搜索得分"50"和鲍勃"的名称,并在该组合存在的情况下获得该指数的索引?有比我提出的更好的方法吗?
Is there a way I can search for score of '50' and name of 'Bob' together and get the index to that only if that combo exists? Is there a better way do do than what I've come up with?
您可以将搜索查询构建为数组,然后将每个项目的交集与之进行比较.
You can build your search query as an array and compare the intersection of each item with it.
$search = ['score' => '50', 'name' => 'Bob'];
foreach($data_info_array as $k => $v) {
if ( $search === array_intersect($v, $search) ) {
echo $k;
break;
}
}
@mickmackusa注意到在这里使用 array_intersect_assoc()
更安全.他说对了,因为当多维数组项不可预测时,没有什么禁止这样的项:
@mickmackusa noticed it is safer to use array_intersect_assoc()
here. He's right because when the multi-dimensional array items are unpredictable, nothing forbids to have items like that:
['miaou' => '50', 'graou' => 'Bob', 'score' => '50', 'name' => 'Bob']
除其他键外,还显示搜索到的值.在这种情况下, array_intersect()
返回 all 正确的值(当然还有它们的对应键),而不管 $ search
中的键是什么,以及与搜索数组将返回 false
.
where the searched values are also present but for other keys. In this case array_intersect()
returns all correct values (with their corresponding keys of course) regardless the keys in $search
, and the comparison with the search array will return false
.
但是使用 array_intersect_assoc()
,可以确保只考虑 $ search
中键的值.
But using array_intersect_assoc()
, you ensure that only values for keys in $search
are taken in account.
结论:如果您被多维数组项目的单调看似迷住了睡眠,那么您将无法免受
Conclusion: If you let yourself be lulled into sleep by the seeming monotony of multidimensional array items, you won't be immune to surprise when unexpected variations arise.