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'

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.