PHP中如何对具有相同数组值的值进行求和
P粉401527045
P粉401527045 2023-09-10 15:14:41
0
1
522

我合并了两个数组(都从不同的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粉401527045
P粉401527045

全部回复(1)
P粉464082061

我会在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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!