IceFire
IceFire

Reputation: 4137

Reduce array of associative arrays to associative array

Is there an idiomatic way (some existing function) to reduce

[[0 => 'zero'], [1 => 'one']]

to

[0 => 'zero', 1 => 'one']

?

It is easy to just create a loop that does the job, but it seems inefficient, and I would clearly prefer a one-liner here.

Edit: Oh, and it is just random here that 0 and 1 follow each other. The array could also be [[2 => 'two'], [3 => 'three']]

Upvotes: 4

Views: 888

Answers (2)

Dan Chadwick
Dan Chadwick

Reputation: 361

Assuming that you want keys preserved, and assuming that in the case of conflicting keys, you want the first value, array_reduce is well-suited to the task.

$r = array_reduce($a, function ($acc, $v) { return $acc + $v; }, []);

This is functionally identical to @Rakesh Jakhar's solution. I think it's semantically more faithful to the problem and avoids having the initialize $r and the use clause.

In php 7.4, this could be written a bit nicer with an arrow function:

$r = array_reduce($a, fn($acc, $v) => $acc + $v, []);

https://www.php.net/manual/en/function.array-reduce.php

Upvotes: 0

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_merge with ... splat operator

$a = [[0 => 'zero'], [1 => 'one']];
print_r(array_merge(...$a));

Solution II: Preserve keys

$a = [[1 => 'one'], [0 => 'zero']];
$r = [];
array_walk($a, function($v, $k) use (&$r){ $r += $v;});
print_r($r);

Working demo : https://3v4l.org/9sRaE

Upvotes: 6

Related Questions