简体   繁体   中英

Sum of array for same values

I have this array:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 10
  )
  [2] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 18
  )
)

How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?

Like this:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 28
  )
)

Something like this maybe:

$final = array();
foreach ($arr as $subarr)
{
    if (!isset($final[$subarr['TaxeName']]))
    {
        $final[$subarr['TaxeName']] = array('Price' => 0);
    }
    $final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeAmount'];
    $final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeName'];
    $final[$subarr['TaxeName']]['Price'] = $final[$subarr['TaxeName']]['Price'] + $subarr['Price'];
}

The idea is to make a new array with the values that you need and initializing it with the price set to 0 so you can increment it in the foreach

You can do it like this also:

<?php

// Source
$myData = array(
    array(
        'TaxeName' => 'TPS',
        'TaxeAmount' => 7,
        'Price' => 14,
    ),
    array(
        'TaxeName' => 'TVQ',
        'TaxeAmount' => 9.975,
        'Price' => 10,
    ),
    array(
        'TaxeName' => 'TVQ',
        'TaxeAmount' => 9.975,
        'Price' => 18,
    )
);

// Helper Function
function parseData($data)
{
    $parsedData = array();

    if (is_array($data)) {
        foreach ($data as $dataItem) {
            if (!array_key_exists($dataItem['TaxeName'], $parsedData)) {
                $parsedData[$dataItem['TaxeName']] = array(
                    'TaxeName' => $dataItem['TaxeName'],
                    'TaxeAmount' => $dataItem['TaxeAmount'],
                    'Price' => floatval($dataItem['Price'])
                );
            } else {
                $parsedData[$dataItem['TaxeName']]['Price'] += floatval($dataItem['Price']);
            }
        }
    }

    return array_values($parsedData);
}

// Test
$parsed_data = parseData($myData);
var_dump($parsed_data);

?>

Outputs:

在此处输入图片说明

It can be done with a nested foreach :

$original = array(.......); // your current array
$newArr = array();

foreach($original as $origVal){
    $exists = false;
    foreach($newArr as $key => $newVal){
        if($newVal['TaxeName'] == $origVal['TaxeName']){
            $newArr[$key]['Price'] += $origVal['Price'];
            $exists = true;
            break;
        }
    }

    if(!$exists){
        $newArr[] = $origVal;
    }
}

Outputs

Array
(
    [0] => Array
        (
            [TaxeName] => TPS
            [TaxeAmount] => 7
            [Price] => 14
        )

    [1] => Array
        (
            [TaxeName] => TVQ
            [TaxeAmount] => 9.975
            [Price] => 28
        )

)

Just use this function, input is your array, output is the array you required:

function calculate(array $input){
    $output = [];
    foreach ($input as $v){
        if (array_key_exists($v['TaxeName'], $output)){
            $output[$v['TaxeName']]['Price'] += $v['Price'];
        } else {
            $output[$v['TaxeName']] = $v;
        }
    }

    return array_values($output);
}

I know that solutions with external classes are not welcome here on SO. I'm showing this just to illustrate the "Grouping the TaxeName and the TaxeAmount" task.

//use class tablearray from https://github.com/jspit-de/tableArray
$data = [
  ['TaxeName' => 'TPS', 'TaxeAmount' => 7, 'Price' => 14],
  ['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 10],
  ['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 18],
  ['TaxeName' => 'TVQ', 'TaxeAmount' => 19.975, 'Price' => 23]
];

$newData = tableArray::create($data)
  ->filterGroupSum('Price',['TaxeName','TaxeAmount'])
  ->fetchAll()
;

echo '<pre>';
var_export($newData);

Output:

array (
  0 => 
  array (
    'TaxeName' => 'TPS',
    'TaxeAmount' => 7,
    'Price' => 14,
  ),
  1 => 
  array (
    'TaxeName' => 'TVQ',
    'TaxeAmount' => 9.975,
    'Price' => 28,
  ),
  2 => 
  array (
    'TaxeName' => 'TVQ',
    'TaxeAmount' => 19.975,
    'Price' => 23,
  ),
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM