I have an array and search for the value 100 - the result should gives me the key of the array. this works like this:
$myArray = array(
array(
'score' => '100',
'name' => 'Sam',
'subject' => 'Data Structures'
),
array(
'score' => '200',
'name' => 'Tanya',
'subject' => 'Advanced Algorithms'
),
array(
'score' => '300',
'name' => 'Jack',
'subject' => 'Distributed Computing'
)
);
$id = array_search('100', array_column($myArray, 'score'));
But now the "column" score should be an array, too:
$myArray = array(
array(
'score' => array('100','200'),
'name' => 'Sam',
'subject' => 'Data Structures'
),
array(
'score' => array('300','400'),
'name' => 'Tanya',
'subject' => 'Advanced Algorithms'
),
array(
'score' => array('500','600'),
'name' => 'Jack',
'subject' => 'Distributed Computing'
)
);
But now my array_search part doesn't work. How can I solve this?
CodePudding user response:
You can use array_filter
and then use in_array
on the scores
key thus returning arrays that have a value of 100
.
array_filter($myArray, fn($v) => in_array(100, $v['score']));
Output:
array(1) {
[0]=>
array(3) {
["score"]=>
array(2) {
[0]=>
string(3) "100"
[1]=>
string(3) "200"
}
["name"]=>
string(3) "Sam"
["subject"]=>
string(15) "Data Structures"
}
}
CodePudding user response:
This works exactly the same way as your first block
$id = array_search(100, array_merge(array_column(array_column($myArray, 'score'), 0), array_column(array_column($myArray, 'score'), 1)));
OR you can write it this way for readability
$tempArray1 = array_column(array_column($myArray, 'score'), 0);
$tempArray2 = array_column(array_column($myArray, 'score'), 1);
$myArray2 = array_merge($tempArray1, $tempArray2);
$id = array_search('100', $myArray2);