基于 php 子数组中相同键的数组总和

Sum totals in array based on same keys in subarray in php

我正在尝试根据相同的键将总数加起来。

这是我的数组

[
    {
        "tipe": "IT",
        "kode": "302.1259",
        "total": "5"
    },
    {
        "tipe": "ADM",
        "kode": "302.1122",
        "total": "2"
    },
    {
        "tipe": "IT",
        "kode": "302.1000",
        "total": "10"
    },
    {
        "tipe": "SUPPORT",
        "kode": "302.2389",
        "total": "10"
    },
]

我想根据同一个键将总数加起来。 我希望输出是这样的

[
        {
            "tipe": "IT",
            "total": "15" 
        },
        {
            "tipe": "ADM",
            "total": "2"
        },
        {
            "tipe": "SUPPORT",
            "total": "10"
        },
    ]

这是我编写的代码,但我仍然无法根据相同的密钥将总数加起来

 public function getView()
    {
        $sum = 0;
        $hasil = array();
        
        $satu = $this->my_model->getDB()->result_array();
        foreach($satu as $key =>$val){
            $cek = $this->my_model->cek_kode($val['kode'])->num_rows();
            if ($cek > 0 ) {
               $val['total'] = 0;
            }
            $sum += $val['total'];
            
            $hasil[] = array(
            'tipe'     => $val['tipe'],
            'total'    => number_format($sum),
            );  
        }
        $response =  $this->set_response($hasil,200);    
    }

我创建了上面的函数,但它不起作用

根据您提供的数组,您可以这样加总:

$array = [
    [
        "tipe" => "IT",
        "kode" => "302.1259",
        "total" => "5"
    ],
    [
        "tipe" => "ADM",
        "kode" => "302.1122",
        "total" => "2"
    ],
    [
        "tipe" => "IT",
        "kode" => "302.1000",
        "total" => "10"
    ],
    [
        "tipe" => "SUPPORT",
        "kode" => "302.2389",
        "total" => "10"
    ]
];

$totals = [];

foreach ($array as $item) {
    if (!array_key_exists($item['tipe'], $totals)) {
        $totals[$item['tipe']] = (int)$item['total'];
        continue;
    }

    $totals[$item['tipe']] += (int)$item['total'];
}