Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid array_merge in loops when dealing with array of objects

There are a bunch of discussions around 'array_merge(...)' is used in a loop and is a resources greedy construction.

For simple arrays there is an easy solution using the spread operator. E.g.

$arraysToMerge = [ [1, 2], [2, 3], [5,8] ];
$arraysMerged = array_merge([], ...$arraysToMerge);

However, my problem is that I couldn't find a way to avoid it in the following scenario:

Say you have a list of users and each use has multiple social media accounts.

How would you create an array that has all the social media accounts from all the users? The only solution I found is something like this:

$allSocialMediaAccounts= [];
foreach ($users as $user) {
    $allSocialMediaAccounts= array_merge($accounts, $user['socialMediaAccounts']);
}
like image 218
JakobAttk Avatar asked Oct 27 '25 04:10

JakobAttk


1 Answers

You can get the $arraysToMerge using the array_column() function on $users like this:

$arraysToMerge = array_column($users, 'socialMediaAccounts');
$arraysMerged  = array_merge(...$arraysToMerge);

Matt suggested that you don't need to merge into an empty array, so I adapted the code to his suggestion.

like image 144
KIKO Software Avatar answered Oct 29 '25 17:10

KIKO Software



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!