简体   繁体   中英

PHP array sum values

I'm having this array:

array(
[1] => Array
    (
        [1111] => Array
            (
                [one] => 70
                [two] => 7.0
            )

    )

[2] => Array
    (
        [1111] => Array
            (
                [one] => 10
                [two] => 2.0
            )

    )
)

And i want it to sum [one] and [two] of the two different arrays and output an array like this:

Array
(
    [1111] => Array (
        [one] => 80
        [two] => 9.0
    )
)

Based on the key "1111"

I have tried with the following

$array = array_values( $array );
$sum_array = [];

foreach ( $array as $k => $sub_array ) {
    foreach ( $sub_array as $id => $value ) {
        $sum_array[$id]            += array_key_exists( $id, $sum_array ) ? $sum_array[$id] += $value : $sum_array[$id] = $value;
        $sum_array[$id]['two'] += array_sum( $sum_array[$id]['two'] ) / ( 100 * count( $sum_array[$id]['count'] ) );
    }
}

But that gives me only the first value like this:

Array
(
    [1111] => Array (
        [one] => 70
        [two] => 7.0
    )
)

Can someone please tell me what i'm doing wrong?

You could use the array_reduce to reduce your array to only one element.

The array_reduce function takes two ( sometime three ) parameters. The first one is the array, the second one is a callback with two parameters , the collector, and the current item. If there is a third parameters to the array_reduce function, it will be used to initialize the collector ( like in our case ).

The function will parse each item and do something with it, the collector will be available at each iteration, that's why we use it to keep information of the data, in our case, it's the sum of the values. Once all the item has been iterated over, the function returns the collector.

<?php
$array = [
            [
                '1111' => [
                    'one' => 70,
                    'two' => 7.0
                ]
            ],
            [
                '1111' => [
                    'one' => 10,
                    'two' => 2.0
                ]
            ]
    ];

    $output = array_reduce($array, function($collector, $item) {
        $collector['1111']['one'] += $item['1111']['one'];
        $collector['1111']['two'] += $item['1111']['two'];
        return $collector;
    }, ['1111' => ['one' => 0, 'two' => 0]]);

    var_dump($output);

Here is an approach that uses a recursive merge. In the following when merged John's hours become an array. We then need to sum. As James only has one entry his hours do not become an array so we leave them be.

Hopefully the transitional merge output, will give you an idea of the process:

<?php

$items = 
[
    [
        'john' => [
            'hours' => 2,
            'tips' => 7
        ]
    ],
    [
        'john' => [
            'hours' => 3,
            'tips' => 10
        ]
    ],
    [
        'james' => [
            'hours' => 8,
            'tips' => 0
        ]
    ]
];

$output = array_merge_recursive(...$items);
var_export($output);

array_walk($output, function(&$v) {
    array_walk($v, function(&$v) {
        if(is_array($v))
            $v = array_sum($v);
    });
});
echo "\nResult: \n";
var_export($output);

Output:

array (
  'john' => 
  array (
    'hours' => 
    array (
      0 => 2,
      1 => 3,
    ),
    'tips' => 
    array (
      0 => 7,
      1 => 10,
    ),
  ),
  'james' => 
  array (
    'hours' => 8,
    'tips' => 0,
  ),
)
Result: 
array (
  'john' => 
  array (
    'hours' => 5,
    'tips' => 17,
  ),
  'james' => 
  array (
    'hours' => 8,
    'tips' => 0,
  ),
)
$total=0;
array_map(function ($item) use ($total)
{
    $total += $item['one'] + $item['two'];
}, $array);


echo $total;

Or difference key



$one = array_sum(array_column($array, 'one'));
$two = array_sum(array_column($array, 'two'));

$resultArray = compact('one','two');

```

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