0

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;
    });
2
  • 3
    Why though? If you don't use a third variable and update the main array directly... You might overwrite indexes. For example, if you have an id 30, but also have an item at index 30, it will overwrite it when you set the id. Commented Aug 15, 2017 at 13:48
  • Just feel that there should be a more elegant and right way to do it. Something like $formatted = array_magic($array, 'id') Commented Aug 15, 2017 at 13:55

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In my opinion this is good, I can't see a reason why the second layer array is needed at all. What is wrong with[30] => "3"?
But I need to get rid of 'id' key. That is the catch.
2

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
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.