简体   繁体   English

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

[英]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,
)

So, first you need $amountsArray to get assigned the values you listed, somehow.因此,首先您需要$amountsArray以某种方式分配您列出的值。 Then:然后:

$bankTotals = array();
foreach($amountsArray as $amount)
{
  $bankTotals[$amount['name']] += $amount['amount'];
}

Output: ( Demo )输出:(演示

Warning: Undefined array key "Bank BRI"

Warning: Undefined array key "Bank BCA"

Warning: Undefined array key "Bank CIMB Niaga"

Warning: Undefined array key "Bank BNI"

Warning: Undefined array key "Bank Mandiri"

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

After this, $bankTotals is an array indexed on name of the bank, with the value of the total amount for the bank.在此之后, $bankTotals是一个以银行名称为索引的数组,其中包含银行总金额的值。 You can use this array as you see fit from here.您可以从此处按照您认为合适的方式使用此数组。

One thing that might be useful is another foreach loop to print it all out:可能有用的一件事是另一个foreach循环将其全部打印出来:

foreach($bankTotals as $name => $amount)
{
  echo $name.".....".$amount."\n";
}
<?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;
}

I would rather add我宁愿添加

$bankTotals = array();
foreach($amountsArray as $amount)
{
 if(isset($bankTotals[$amount['name']]))
    $bankTotals[$amount['name']] += $amount['amount'];
 else
    $bankTotals[$amount['name']] = $amount['amount'];
}

Example in C#: C# 中的示例:

Dictionary<string,object>[] items = {
  new Dictionary<string, object> {{ "name", "Bank BRI"}, {"amount", 0 }},
  new Dictionary<string, object> {{ "name", "Bank BRI"}, {"amount", 0 }},
  new Dictionary<string, object> {{ "name", "Bank BCA"}, {"amount", 1412341234 }},
  new Dictionary<string, object> {{ "name", "Bank CIMB Niaga"}, {"amount", 532532552 }} 
};

var amounts = new Dictionary<string, int>();

foreach (var item in items) {
  string bank = (string)item["name"];
  int amount = (int)item["amount"];
  if (amounts.ContainsKey(bank)) {
    amounts[bank] += amount;
  } else {
    amounts.Add(bank, amount);
  }
}

foreach (var amount in amounts) {
  Console.WriteLine("{0}: {1}", amount.Key, amount.Value);
}

@Shubham's loop is a perfectly adequate technique. @Shubham 的循环是一种非常合适的技术。

You may wish to employ array_reduce() if you want to:如果您愿意,您可能希望使用array_reduce()

  • avoid generating a global-scoped variable or避免生成全局范围的变量或
  • want to work with a returned value or想要使用返回值或
  • generally prefer a functional style通常更喜欢功能风格

The null coalescing operator prevents generating any warnings/errors from adding to not-yet-declared elements in the result array空合并运算符可防止生成任何警告/错误以添加到结果数组中尚未声明的元素

Code: ( Demo )代码:(演示

var_export(
    array_reduce(
        $array,
        function($carry, $row) {
            $carry[$row['name']] = ($carry[$row['name']] ?? 0) + $row['amount'];
            return $carry;
        }
    )
);

Or from PHP7.4 with arrow function syntax: ( Demo )或者来自 PHP7.4 的箭头函数语法:( Demo )

var_export(
    array_reduce(
        $array,
        fn($carry, $row) => array_merge($carry, [$row['name'] => ($carry[$row['name']] ?? 0) + $row['amount']]),
        []
    )
);

Output:输出:

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

foreach ($a as $anarrays) {
        echo "$anarrays[name]."  ".$anarrays[amount]";
    }
}

see foreach in php.见 php 中的 foreach。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对数据行进行分组,并在每组中汇总一列并连接另一列 - Group rows of data and in each group sum one column and concatenate another column 根据两列值和每组中一列的总和对多维数组数据进行分组 - Group multidimensional array data based on two column values and sum values of one column in each group 按一列对二维数组数据进行分组,并对每组中的其他列求和(分别) - Group 2d array data by one column and sum other columns in each group (separately) 按 3 列对数据行进行分组,并对各个组中的另一列求和 - Group rows of data by 3 columns and sum another column within respective groups 将一列上的行分组并从另一列创建嵌套数组 - Group rows on one column and create nested array from another column 按一个列值对行进行分组,对另一列求和并计算出现次数 - Group rows by one column value, sum another column and count occurrences 将数据从一列移到另一mysql - move data from one column to another mysql 按一列对多维数组进行分组并对另一列求和 - Group multidimensional array by one column and sum the other column SQL复制数据从一列到另一个表指定列 - SQL copy data from one column to another table specified column SQL - 将数据从一个表列复制到另一个表列 - SQL - copy data from one table column to another table column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM