Array mapping in PHP with keys
arrays, dictionary, php
Solution
Just use `array_reduce`:
$obj1 = new stdClass;
$obj1 -> id = 12;
$obj1 -> name = 'Lorem';
$obj1 -> email = 'lorem@example.org';
$obj2 = new stdClass;
$obj2 -> id = 34;
$obj2 -> name = 'Ipsum';
$obj2 -> email = 'ipsum@example.org';
$reduced = array_reduce(
// input array
array($obj1, $obj2),
// fold function
function(&$result, $item){
// at each step, push name into $item->id position
$result[$item->id] = $item->name;
return $result;
},
// initial fold container [optional]
array()
);
It's a one-liner out of comments ^^
Problem
Just for curiosity (I know it can be a single line `foreach` statement), is there some PHP array function (or a combination of many) that given an array like: ``` Array ( [0] => stdClass Object ( [id] => 12 [name] => Lorem [email] => lorem@example.org ) [1] => stdClass Object ( [id] => 34 [name] => Ipsum [email] => ipsum@example.org ) ) ``` And, given `'id'` and `'name'`, produces something like: ``` Array ( [12] => Lorem [34] => Ipsum ) ``` I use this pattern a lot, and I noticed that `array_map` is quite useless in this scenario cause you can't specify keys for returned array.