ditto
ditto

Reputation: 6277

Searching nested arrays and returning the key from a matching value

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

Upvotes: 0

Views: 72

Answers (3)

Cristik
Cristik

Reputation: 32806

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.

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

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

Upvotes: 1

viral
viral

Reputation: 3743

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);

Upvotes: 0

Related Questions