Howto use array_map functionality on an associative array to change values *and* keys
November 9, 2012
$assoc_arr = array_reduce($arr, function ($result, $item) {
$result[$item['text']] = $item['id'];
return $result;
}, array());
The snippets story
I just ran into a problem with extracting data from an array, like the following one:
$arr = array(
array(
'id' => 22,
'text' => 'Lorem'
),
array(
'id' => 25,
'text' => 'ipsum'
),
);
From this array, I wanted to create another, associative array, with the following structure:
$assoc_arr = array( 'Lorem' => 22, 'ipsum' => 25 );
My first guess was the array_map function, but I had to realize that there is no way to manipulate the keys of the resulting array. After some googling, I discovered, that it is array_reduce you have to use for such a thing.
ps: I know, a simple foreach would have done the trick, but once on the path of functional programming, I didn’t want to leave it that fast