I've this piece of code in which I want to know is there anyway I could avoid pass by reference
public function formatNumbers($numbersData){
$result = array();
array_map(
function($row) use (&$result) {
$result[$row['GroupId']][$row['Type']] = $row['value'];
}, $numbersData
);
return $result;
}
Input: $numbersData =
Array
(
[0] => Array
(
[GroupId] => 2
[Type] => 1
[value] => 82000
)
[1] => Array
(
[GroupId] => 2
[Type] => 3
[value] => 52000
)
[2] => Array
(
[GroupId] => 2
[Type] => 4
[value] => 30105
)
[3] => Array
(
[GroupId] => 2
[Type] => 7
[value] => 13266
)
)
Output is
Array
(
[2] => Array
(
[1] => 82000
[3] => 52000
[4] => 30105
[7] => 13266
)
)
I know I can do it using foreach, but I want to know that if there anyway to use array map for this without pass by reference.Any help would be greatly appreciated.
Wrong kind of operation. You're not looking for a mapping of values, you're looking for an array reduction:
return array_reduce($numbersData, function(array $acc, array $row) {
$acc[$row['GroupId']][$row['Type']] = $row['value'];
return $acc;
}, []);