Skip to content
Advertisement

PHP – Sum Array key value where 2 or more other keys are equal while keeping array structure

I have this source array():

$source[]

JavaScript

My goal is to reduce it so that i get only 1 item where user_id & item_id are the same:

$result[]

JavaScript

The ultimate way would be to use an array_reduce, but i’ll take a foreach loop.

I’ve tried this, but i get an empty array

JavaScript

or this, but i get an array with user_id as index and quantity as value as a overall total, not seperate by item_id:

JavaScript

I’m starting to try with a foreach loop with if (isset[...]) but i feel like it will return true whatever the index of the $result[] array.

Advertisement

Answer

You can use array_reduce function in next way:

JavaScript

PHP array_reduce online

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement