How to sum values with the same array value in PHP
P粉401527045
P粉401527045 2023-09-10 15:14:41
0
1
446

I merged two arrays (both taken from different mysql tables) and now I want to sum all elements in the arrays with the same value.

$merged_arr = array_merge($reg, $rel);

Array ( [0] => Array ( [DEPARTMENT] => LEAFSPRINGDIRECT [BASIC INCOME] => 3035.37 [OT PAY] => 0 ) [1] => Array ( [DEPARTMENT] => MUFFLERDIRECT [BASIC INCOME] => 24962.09 [OT PAY] => 5358.76 ) [2] => Array ( [DEPARTMENT] => MUFFLERDIRECT [BASIC INCOME] => 14082.080000000002 [OT PAY] => 3248.4 ) )

This is what I tried, but I had to use if-else statements over and over again.

foreach($merged_arr as $key => $val) { // echo $val['BASIC INCOME']."
"; // echo array_keys(array_values($new_arr)[$key])[$count]."-".array_values(array_values($new_arr)[$key])[$count]."
"; if(array_values(array_values($new_arr)[$key])[$count] == "RADIATORDIRECT") { $new_arr['BASIC INCOME'] += '...'; } $count++; }

The array I want should be like this:

Array ( [0] => Array ( [DEPARTMENT] => LEAFSPRINGDIRECT [BASIC INCOME] => 3035.37 [OT PAY] => 0 ) [1] => Array ( [DEPARTMENT] => MUFFLERDIRECT [BASIC INCOME] => 39044.17‬ [OT PAY] => 8607.16‬ ) )

Is there any easier way? Thank you in advance.

P粉401527045
P粉401527045

reply all (1)
P粉464082061

I would do this on the SQL side:

SELECT DEPARTMENT, SUM(`BASIC INCOME`) AS `BASIC INCOME`, SUM(`OT PAY`) AS `OT PAY` FROM ( SELECT DEPARTMENT, `BASIC INCOME`, `OT PAY` FROM `table_a` -- WHERE ... UNION ALL SELECT DEPARTMENT, `BASIC INCOME`, `OT PAY` FROM `table_b` -- WHERE ... ) UNIONS GROUP BY DEPARTMENT
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!