沃梦达 / 编程问答 / php问题 / 正文

在一列上对数组数据进行分组,并对另一列中的数据求和

Group array data on one column and sum data from another column(在一列上对数组数据进行分组,并对另一列中的数据求和)

本文介绍了在一列上对数组数据进行分组,并对另一列中的数据求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组数据如下所示:

I have my array data as shown below:

$array = [
    ['name' => 'Bank BRI', 'amount' => 0], 
    ['name' => 'Bank BRI', 'amount' => 0], 
    ['name' => 'Bank BCA', 'amount' => 1412341234],
    ['name' => 'Bank CIMB Niaga', 'amount' => 532532552], 
    ['name' => 'Bank BRI', 'amount' => 34534534], 
    ['name' => 'Bank CIMB Niaga', 'amount' => 453425243], 
    ['name' => 'Bank BRI', 'amount' => 0], 
    ['name' => 'Bank BNI', 'amount' => 124124], 
    ['name' => 'Bank CIMB Niaga', 'amount' => 352345623], 
    ['name' => 'Bank BCA', 'amount' => 23432423], 
    ['name' => 'Bank Mandiri', 'amount' => 0], 
    ['name' => 'Bank BCA', 'amount' => 0], 
    ['name' => 'Bank BCA', 'amount' => 0], 
    ['name' => 'Bank Permata', 'amount' => 352352353],
];

如何根据相同的银行名称"计算金额".

How to sum 'amount' based on same 'bank name'.

我的结果应该显示分组名称及其总和:

My result should show grouped names and their summed amount:

array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)

推荐答案

<?php

// array of bank structure
$banks = array();
$banks[] = array('name'=>'Bank BRI','amount'=>rand());
$banks[] = array('name'=>'Bank BRI','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank CIMB','amount'=>rand());
$banks[] = array('name'=>'Bank BRI','amount'=>rand());
$banks[] = array('name'=>'Bank CIMB','amount'=>rand());
$banks[] = array('name'=>'Bank BRI','amount'=>rand());
$banks[] = array('name'=>'Bank BNI','amount'=>rand());
$banks[] = array('name'=>'Bank CIMB','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank Mandiri','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank Permata','amount'=>rand());

// begin the iteration for grouping bank name and calculate the amount
$amount = array();
foreach($banks as $bank) {
    $index = bank_exists($bank['name'], $amount);
    if ($index < 0) {
        $amount[] = $bank;
    }
    else {
        $amount[$index]['amount'] +=  $bank['amount'];
    }
}
print_r($amount); //display 

// for search if a bank has been added into $amount, returns the key (index)
function bank_exists($bankname, $array) {
    $result = -1;
    for($i=0; $i<sizeof($array); $i++) {
        if ($array[$i]['name'] == $bankname) {
            $result = $i;
            break;
        }
    }
    return $result;
}

这篇关于在一列上对数组数据进行分组,并对另一列中的数据求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在一列上对数组数据进行分组,并对另一列中的数据求和

基础教程推荐