Search code examples
phparrayslaravelarray-map

Overwrite keys from array by another arrays values


I have two arrays. The array "texts" and the array "dbTexts". In "dbTexts" all texts of a certain category are in my database.

A record looks something like this:

0 => {
   id: 1
   de: "German text"
   en: "English text"
   name: "question"
},
1 => {
   id: 2
   de: "German text"
   en: "English text"
   name: "error"
},
2 => {
   id: 3
   de: "German text"
   en: "English text"
   name: "success"
},

Now I want to manipulate the $texts array and add a key/value for every element of the $dbTexts array.

I want the keys of $texts to be the "name" key of $dbTexts and the value should be either the "de" key or the "en" key.

What I've tried:

$texts = array_map(function ($key) {
     return $texts[$key['name']] = $key[app()->getLocale()];
},$dbTexts->toArray());

app()->getLocale() automatically returns "de" or "en".

So $key would be every element of $dbTexts.

$texts[$key['name']] should return 'question' in the first example record and $key[app()->getLocale()] should return the de/en value of each element.

The output I want to have is:

$texts = [
 'question' => 'German text',
 'error' => 'German text',
 'success' => 'German text',
]

This whole de/en thing isn't important for this question. It's more that I want to create the $texts variable which will hold the "name" of every $dbText as a key and the associated value of de/en from the current $dbText.


Solution

  • This is most easily achieved with a simple foreach loop:

    foreach ($dbTexts->toArray() as $text) {
        $texts[$text['name']] = $text[app()->getLocale()];
    }
    

    Simplified demo on 3v4l.org

    An alternate solution would be to use array_column to re-index the array:

    $texts = array_column($dbTexts->toArray(), app()->getLocale(), 'name');
    

    Simplified demo on 3v4l.org