Reputation: 340
I have the next array
[
['id' => 30, 'count' => 3],
['id' => 45, 'count' => 7]
]
I need it to be
[
30 => ['count' => 3],
45 => ['count' => 7]
]
What I did
$formatted = [];
foreach ($services as $service) {
$formatted[$service['id']] = [
'count' => $service['count']
];
}
What I'd like is a more elegant solution without the temporary $formatted variable. Thanks!
Update. Thanks a lot @rtrigoso ! With the laravel collection, my code looks next
$services->reduce(function ($carry, $item) {
$carry[$item['id']] = ['count' => $item['count']];
return $carry;
});
Upvotes: 0
Views: 50
Reputation: 17417
You can do this in one line with array_column
:
$array = array_column($array, null, 'id');
The one difference between your desired output is that this will still contain the id
key in the second level of the array, like so:
[
30 => ['id' => 30, 'count' => 3],
45 => ['id' => 45, 'count' => 7],
]
but that hopefully shouldn't cause any problems. If you do need to remove it, you can do it with something like:
$array = array_map(function ($e) {
unset($e['id']);
return $e;
}, $array);
This approach is probably best if your rows could potentially have a lot more keys in them in future, i.e. it's quicker to list the keys to remove rather than the ones to keep. If not, and you'll only have a count, then to be honest your original example is probably the best you'll get.
Upvotes: 5
Reputation: 792
You can use array_reduce
$x_arr = array(
array('id' => 30, 'count' => 3),
array('id' => 45, 'count' => 7),
);
$y_arr = array_reduce($x_arr, function ($result, $item) {
$result[$item['id']] = array('count' => $item['count']);
return $result;
}, array());
print_r($y_arr);
It will give you your desired result:
Array
(
[30] => Array
(
[count] => 3
)
[45] => Array
(
[count] => 7
)
)
Upvotes: 2