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.

4
  • 1
    $sumOfAll = array_sum(array_column($rows, 6))*count($rows); Commented Jan 25, 2019 at 10:36
  • @splash58 6 where do you get that from? Commented Jan 25, 2019 at 10:38
  • It the same as your last question (stackoverflow.com/questions/54361937/…) please avoid this - if the last not relevant remove it Commented Jan 25, 2019 at 10:40
  • I should have edit it. Thanks. @dWinder Commented Jan 25, 2019 at 10:41

2 Answers 2

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

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

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.