简体   繁体   中英

Count and sum multidimensional array php

I have an array like this one:

    array (size=1)
  0 => 
    array (size=33)
      0 => int 126
      1 => int 43
      2 => int 4
      3 => int 0
      4 => int 3
      5 => int 3
      6 => int 30
      7 => int 15
      8 => int 22
      9 => int 27
      10 => int 22
      11 => int 46
      12 => int 0
      13 => int 8
      14 => int 14
      15 => int 8

array (size=1)
  1 => 
    array (size=33)
      0 => int 273
      1 => int 3
      2 => int 4
      3 => int 28
      4 => int 36
      5 => int 19
      6 => int 142
      7 => int 81
      8 => int 59
      9 => int 71
      10 => int 88
      11 => int 47
      12 => int 42
      13 => int 0
      14 => int 12
      15 => int 97

(of course it is way longer) and I need both to sum all the value with the same key and count how many values with the same key are >0 (cause I have to find the avarage of all the numbers >0

My expected result is

0=>
   'sum' => 399
   'count'=>2
1=>
   'sum' =>46
   'count'=>2

how can I create this array?

There's an inbuilt function in PHP to count the sum of all the elements of an array. Here, this will give you your expected output :

<?php
    $arr = [[10, 20, 30, 40], [10, 20, 30], [10, 20, 30, 4]];
    // Let the magic happen...
    $yourArray = array_map(function ($el){ return ["sum" => array_sum($el), "count" => count($el)]; }, $arr);

    print_r($yourArray);
?>

I have thought about this, and came up with a solution (I think...), it comes in the form of a function and it goes like this:

function getSumAndCount(array $arr)
{
    $sum = 0;
    $count = 0;
    foreach ($arr as $v)
    {
        $count++;
        if (is_array($v))
        {
            $next = getSumAndCount($v);
            $count += $next['count'];
            $sum += $next['sum'];
        }
        else
        {
            !is_numeric($v) ?: $sum += $v;
        }
    }

    return [ 'sum' => $sum, 'count' => $count ];
}

It has a recursive check to if the array is multidimensional, checks if the value is numeric and sets the count and sum in a return array.

I haven't tested this properly as yet, but please test and let me know if you get the desired output.

EDIT
I will extend this to count dupe keys soon

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