S.M*_*son 3 php arrays filter multidimensional-array
给定以下二维数组:
$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;
Run Code Online (Sandbox Code Playgroud)
如果我想按两个值进行搜索,我只能想到如下:
$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;
Run Code Online (Sandbox Code Playgroud)
有没有办法我可以一起搜索“50”的分数和“Bob”的名字,并仅在该组合存在时才获取该索引?有比我想出的更好的方法吗?
您可以使用array_filter(),它允许您同时对内容进行尽可能多的检查...
$output = array_filter($data_info_array, function ($data) {
return $data['score'] == 50 && $data['name'] == 'Bob';
});
Run Code Online (Sandbox Code Playgroud)
这将为您提供匹配列表,因此[0]如果您需要单个匹配,您可能需要执行此操作(并检查是否仅返回 1)。