php sum values of multiple subarrays if subarrays are not the same length (not the same number of keys)

StackOverflow https://stackoverflow.com/questions/23311371

  •  10-07-2023
  •  | 
  •  

Domanda

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'

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top