S.Mason :
Given the following 2D 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;
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;
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?
Casimir et Hippolyte :
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;
}
}