PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 7, 2022

[FIXED] Sum totals in array based on same keys in subarray in php

 February 07, 2022     arrays, codeigniter, php     No comments   

Issue

I'm trying to add up the total based on the same key.

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"
    },
]

I want to add up the total based on the same key. I hope the output is like this

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

and this is the code I've made, but I still haven't managed to add up the total based on the same key

 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);    
    }

I created the function above but it doesn't work


Solution

Based on the array you provided, you can add up the totals like this:

$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'];
}


Answered By - Gerard de Visser
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing