我正在尝试根据相同的键加总数。
This my 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"
},
]
我想基于相同的键加总数。我希望输出是这样的
[
{
"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'];
}