[
[mile] => [
[acronym] => mi
],
[kilometer] => [
[acronym] => km
]
]
$acronym = 'km';
How may I return the key name from a matching acronym value? In this example I want to return kilometer.
[
[mile] => [
[acronym] => mi
],
[kilometer] => [
[acronym] => km
]
]
$acronym = 'km';
How may I return the key name from a matching acronym value? In this example I want to return kilometer.
This should work for you:
Here I just simply create an array with array_combine() where I use the array_column() with the keyname acronym as keys and the array_keys() from the $arr as values.
<?php
$acronym = "km";
$arr = array_combine(array_column($arr, "acronym"), array_keys($arr));
echo $arr[$acronym];
?>
output:
kilometer
array_column($arr, "acronym") with array_map(function($v){return $v["acronym"];}, $arr). Then it is >=5.3. And if you write the function as normal function and pass the function name as string it it is > 5If your array can have multiple levels, you can use a stack, and you recursively enumerate through the array, and when you encounter an acronym key, you have the full key path in the stack. Something like this:
function findAcronym($array, $keyStack, &$result) {
foreach($array as $key => $value) {
if($key === 'acronym') {
$result[] = $keyStack;
} elseif(is_array($value)) {
$keyStack[] = $key;
findAcronym($value, $keyStack, $result)
}
}
}
you can use the function like this:
$matches =[];
findAcronym($myArray, [], $matches);
$matches will be an array of array of keys, each array of keys corresponding to the key path that gets you to the acronym one.
As the function is recursive, it can go as deep as many levels the array has.