0
[
    [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.

2
  • Have you tried something to get to your goal yourself ? Commented May 14, 2015 at 7:40
  • So where are we with this question? Did any of the answers below helped you? Commented May 14, 2015 at 8:09

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunatly, only php >5.5 :(
@splash58 You can easily change out the 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 > 5
Of course, there are many variants. I just to notify the question autor
@splash58 We live in 2105 so I hope I can assume, that everyone has at least PHP 5.5. Also if you think about, that this year should PHP 7 come out. Then I hope it won't take so long that everyone will use it.
For those who live in 2105 it is really not a problem :))))
0

You can do something like

$array = array(
    'mile'=>array('acronym'=>'mi'),
    'kilometer'=>array('acronym'=>'km')
    );

$acronym = 'km';

function get($each,$acronym)
{

    foreach($each as $k => $v)
    {
        if($v['acronym'] == $acronym)
        {
            return $k;
        }
    }
}

get($array,$acronym);

Comments

0

If 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.