0

I have this array

$languages = array (
    'de' => 
        array (
            'FIRSTNAME' => 'Vorname',
            'SURNAME' => 'Nachname'
        ),
    'en' => 
        array ( 
            'FIRSTNAME' => 'Firstname',
            'SURNAME' => 'Surname'
        )
 );

and I am trying to get the full index (full key) of $languages by using the value of SURNAME for example.

Example: Looking for 'Firstname' should return $languages['en']['FIRSTNAME']

I tried array_search combined with array_column but in fact I don't know the "column" to look for

array_search($value, array_column($array_to_search_in, 'column'));

I also found a solution with array_walk_recursive but only with key comparison, not by value.

array_walk_recursive($languages, function($v, $k, $u) use (&$values){
    if($k == $value) {
        $values[] = $v;
    }
},  $values );

Any help is as always highly appreciated!! Thanks!

3
  • In your array_walk_recursive() code, try swapping the test to be $v == $value and $values[] = $k (you will also need to add $value to your use clause. Commented Apr 30, 2020 at 6:03
  • Thanks for the answer. It is getting close but it only returns Array ( [0] => FIRSTNAME ). I need also the first "key" which is "en" Commented Apr 30, 2020 at 6:14
  • Is your array structure always the same as above (although you may have more options at both levels)? Commented Apr 30, 2020 at 6:27

1 Answer 1

1

Never worked with array_walk_recursive, but IMO you can apply a basic recursive function. This would loop over the data. If value is same as search key, then we return an array which has the current key. If parent recursive call receives an array with size more than 0, we add current parent key to return result as well.

<?php

function search($data,$search_key){
    foreach($data as $key => $value){
        if(is_array($value)){
            $result = search($value,$search_key);
            if(count($result) > 0){
                $result[] = $key;
                return $result;
            }
        }else if($value == $search_key){
            return [$key];
        }
    }

    return [];
}

Demo: https://3v4l.org/Drfpv

Sign up to request clarification or add additional context in comments.

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.