0

I have a function getData that returns:

    array:4 [▼
  0 => array:1 [▼
    0 => "5689.01"
  ]
  1 => array:1 [▼
    0 => "5689.01"

  ]
  2 => array:1 [▼
    0 => "0.0"
  ]
  3 => array:1 [▼
    0 => "5665.11"
   ]
]

I need to COUNT number of rows (this time 4, as above) with values that are returned every time when I trigger a call and return total SUM of all results as listed.

 $rows = $this->get('app')->getData();

 if($rows) {
        foreach ($rows as $row) {
            $sumOfAll = 0;
            $total = count($rows);
            $sumOfAll += array_sum(array($row[0] * $total));

            dump($sumOfAll);die;
    }
}

I always get a wrong sum, in this case it was 22756.04.

John Martin
  • 81
  • 1
  • 9

2 Answers2

4

Use array_sum and array_column to get the values and sum them.
Then use count() to get the count.

$sum = array_sum(array_column($arr, 0));
$count = count($arr);

echo "count is ". $count . " And sum is " . $sum;

https://3v4l.org/HFbgc

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

To fix your sum value, you need to move $sumOfAll variable out side of your foreach

Change your code from this:

foreach ($rows as $row) {
    $sumOfAll = 0;
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));

    dump($sumOfAll);die;
}

to this:

$sumOfAll = 0;
foreach ($rows as $row) {
    $total = count($rows);
    $sumOfAll += array_sum(array($row[6] * $total));
}
dump($sumOfAll);die;
Igor Ilic
  • 1,370
  • 1
  • 11
  • 21