给定以下二维数组:
$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;
如果我想按两个值进行搜索,我只能想到如下:
$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”的分数和“Bob”的名字,并仅在该组合存在时才获取该索引?还有比我想出的更好的方法吗?
您可以使用array_filter()
,它允许您同时对内容进行尽可能多的检查...
$output = array_filter($data_info_array, function ($data) {
return $data['score'] == 50 && $data['name'] == 'Bob';
});
这将为您提供匹配列表,因此您可能需要执行以下操作[0]
(并检查是否只返回 1)如果您需要单个匹配项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)