I really like the functional programming style of using array map to create an array of objects from another array of objects.
$newObjects = array_map(
function($oldObject) {
return new NewObject($oldObject);
},
$oldObjects
);
Which all works fine but I would really like to be able to set the indices of the array so that they are the ids of the original objects for easier search and retrieval from the array but I cannot think how to do it other then which is not as elegant.
$newObjects = array();
foreach ($oldObjects as $oldObject) {
$newObjects[$oldObject->getId()] = new NewObject($oldObject);
}
Is there a way I can do this?
That is -
array_reduce()
is exactly what you need:This will do all in-place without having to spend memory on additional arrays like for
array_combine()
However, I would suggest to use such constructs when they're necessary. Using this just because it "looks better" might be not a good idea - as plain loops are in most cases just more readable.