Skip to content
Advertisement

Group 2D array by id column, push amount into group, and add amount to all previous amounts in group

Using array_key_exists() you would find repeated values and be able to sum them up. In my case, I am not trying to sum all the values and consolidate them into one value. What I am trying to do is to iterate through the values, group by the ac_no value and each subsequent encounter of the same ac_no value, add the new amount to all previously encountered amounts in the group.

Here’s my sample input:

JavaScript

Notice that ac_no value 100001 exists 4 times. In the result, the 100001 group should have the following elements because each absolute value is added to all previous amounts in the group:

JavaScript

My current coding attempt looks like this:

JavaScript

Advertisement

Answer

Three foreach() along with array_sum() and is_array() will do the job (I am considering negative values to be subtracted):

JavaScript

Output : https://3v4l.org/duoEc

Important Update: But as I looked at your calculation closely (based on @mickmackusa comment) I found that you are ignoring the - sign and adding all values as positive. To do so do like below:

JavaScript

Output : https://3v4l.org/j9tkC

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