Agrupe datos de matriz en una columna y sume datos de otra columna para formar una matriz asociativa plana

Resuelto Chandra asked hace 54 años • 5 respuestas

Tengo los datos de mi matriz como se muestra a continuación:

$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],
];

Cómo sumar el "monto" según el mismo "nombre del banco".

Mi resultado debería mostrar nombres agrupados y su cantidad sumada:

array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)
Chandra avatar Jan 01 '70 08:01 Chandra
Aceptado

Entonces, primero debes $amountsArrayque te asignen los valores que enumeraste, de alguna manera. Entonces:

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

Salida: ( Demostración )

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,
)

Después de esto, $bankTotalshay una matriz indexada según el nombre del banco, con el valor del monto total del banco. Puede utilizar esta matriz como mejor le parezca desde aquí.

Una cosa que podría resultar útil es otro foreachbucle para imprimirlo todo:

foreach($bankTotals as $name => $amount)
{
  echo $name.".....".$amount."\n";
}
Jeffrey Blake avatar Jul 20 '2010 03:07 Jeffrey Blake
<?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;
}
 avatar Jul 20 '2010 06:07

preferiría agregar

$bankTotals = array();
foreach($amountsArray as $amount)
{
 if(isset($bankTotals[$amount['name']]))
    $bankTotals[$amount['name']] += $amount['amount'];
 else
    $bankTotals[$amount['name']] = $amount['amount'];
}
 avatar Mar 29 '2017 05:03