搜尋

首頁  >  問答  >  主體

PHP中如何對具有相同數組值的值進行求和

我合併了兩個陣列(都從不同的mysql表中獲取),現在我想將數組中相同值的所有元素求和。

$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
        )
)

這是我嘗試過的方法,但我必須一遍又一遍地使用if-else語句。

foreach($merged_arr as $key => $val) 
    {
        // echo $val['BASIC INCOME']."<br>";

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

        $count++;
    }

我想要的陣列應該是這樣的:

Array
(
    [0] => Array
        (
            [DEPARTMENT] => LEAFSPRINGDIRECT
            [BASIC INCOME] => 3035.37
            [OT PAY] => 0
        )

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

有什麼更簡單的方法嗎?提前謝謝。

P粉401527045P粉401527045430 天前523

全部回覆(1)我來回復

  • P粉464082061

    P粉4640820612023-09-11 13:52:23

    我會在SQL端這樣做:

    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
    

    回覆
    0
  • 取消回覆