1

Have such array (placed code here http://codepad.viper-7.com/mTqf6W)

Array
(
[17,bank stmt,1,23,3,2014] => Array
    (
        [0] => Array
            (
                [RecordDay] => 17
                [Amount] => 1.5
            )
    )
[17,invoice,2,17,3,2014] => Array
    (
        [0] => Array
            (
                [RecordDay] => 17
                [Amount] => 0.21
            )

        [1] => Array
            (
                [RecordDay] => 17
                [Amount] => 1
            )

    )


)

Want to get totals of [Amount] for each subarray. For the first subarray there is only one key, so Total equals to [Amount]. But for the second subarray there are 2 keys (may be more than 2 keys), so in some way need to sum all [Amount]

For [17,bank stmt,1,23,3,2014] would be 1.5, [17,invoice,2,17,3,2014] would be 1.21

Following some examples PHP Array_Sum on multi dimensional array trying to create code. Created

$values = array('Amount' => 0);
$counter = 0;
foreach ($temp_array as $key => $item) {
$values['Amount'] += $item[$counter]['Amount'];
$counter++;
}

Get error 'Notice: Undefined offset: 2'

Community
  • 1
  • 1
Andris
  • 1,434
  • 1
  • 19
  • 34

1 Answers1

3

If you have PHP 5.5+, this can be done with array_column() and array_sum():

foreach ($array as $sub) {
    echo array_sum(array_column($sub, 'Amount'));
}

Use array_map() to extract all the amounts and then array_sum() to sum the values in the array:

foreach ($array as $sub) {
    echo array_sum(array_map(function($item) {
        return $item['Amount'];
    }, $sub));
}

Output:

1.5
1.21

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150