Reputation: 549
I have defined a multi-dimensional array in php and I want to get the index of the 1st level, where a specific inner key has a certain value:
$arr = [
[ [ "a" => "one", "b" => "two", ],
[ "a" => "three", "b" => "four", ],
],
[ [ "a" => "five", "b" => "six", ],
[ "a" => "seven", "b" => "eight", ],
],
];
I want to get the index $i of the 1st level, where $arr[$i][$j]["b"] == "six".
Thus $arr[$i] should resolve to:
array(2) {
[0]=>
array(2) {
["a"]=>
string(4) "five"
["b"]=>
string(3) "six"
}
[1]=>
array(2) {
["a"]=>
string(5) "seven"
["b"]=>
string(5) "eight"
}
}
I could do this with a loop:
function getIndex($needle, $haystack) {
for ($i = 0; $i < count($haystack); $i++) {
for ($j = 0; $j < count($haystack[$i]); $j++) {
if ( $haystack[$i][$j]['b'] == $needle ) {
return $i;
}
}
}
}
$x = $arr[ getIndex('six', $arr) ];
var_dump($x);
Can I achieve this without interation loops? With an expression to filter or search the array, like
$x = $arr[ <expression> ];
Upvotes: 0
Views: 150
Reputation: 57131
A flexible way of trying to achieve this would be to pass a callback to the search function. This callback would be used to filter the data, only if there is a match will there be some data and this can be used to return the index where it matches.
So first a callback which would check the element of the array...
function check($haystack)
{
return $haystack['b'] == 'six';
}
Then the function itself...
function getIndex(callable $filter, array $haystack)
{
// Loop the base level of the array
foreach ($haystack as $index => $subArray) {
// If applying the filter method leaves some data, then it's found
if (array_filter($subArray, $filter)) {
return $index;
}
}
// Return false for not found
return false;
}
Then the actual usage
var_dump(getIndex('check', $arr));
Upvotes: 1