How to group and get average values from PHP multidimensional array

I am trying to figure out a way I can group all of the items with a similar date in the array below and find the average price for the date based on the corresponding price from the array below.

Array
(
    [0] => Array
        (
            [dates] => Array
                (
                    [0] => 2015-05-04
                    [1] => 2015-05-04
                    [2] => 2015-05-04
                    [3] => 2015-05-04
                    [4] => 2015-05-04
                    [5] => 2015-05-03
                    [6] => 2015-05-02
                    [7] => 2015-05-02
                    [8] => 2015-05-02
                    [9] => 2015-05-01
                    [10] => 2015-05-01
                    [11] => 2015-05-01
                    [12] => 2015-05-01
                    [13] => 2015-05-01
                    [14] => 2015-05-01
                    [15] => 2015-04-30
                )

            [prices] => Array
                (
                    [0] => 4.75
                    [1] => 2.0
                    [2] => 2.25
                    [3] => 4.26
                    [4] => 1.98
                    [5] => 6.0
                    [6] => 3.99
                    [7] => 2.5
                    [8] => 4.99
                    [9] => 6.0
                    [10] => 9.95
                    [11] => 4.99
                    [12] => 3.25
                    [13] => 7.5
                    [14] => 7.5
                    [15] => 2.02
                )

        )

)

Ideally, the finished array would give me each of the distinct dates, along with the corresponding average price for the date.

Here is the code I attempted, however, it did not seem to work correctly:

for ($t = 0; $t<sizeof($prices[$i]['dates']); $t++) {
		
		//print '<p>' . $prices[$i]['dates'][$t] . '</p>';
		
		//print_r($tmp[$i]['dates']);
		
		if (!in_array($prices[$i]['dates'][$t], $tmp[$i]['dates'], TRUE)) {
    		$tmp[$i]['dates'][$c] = $prices[$i]['dates'][$t];
			$tmp[$i]['sales'][$c] = $prices[$i]['prices'][$t];
			$c++;
		}
		else {
			$tmp[$i]['sales'][$c] = ($tmp[$i]['sales'][$c] + $prices[$i]['prices'][$t]) / 2;
		}
		
	}

Assuming a 1:1 correspondence on the arrays

<?php
$result = [];

foreach ($dates as $key => $date) {
  if(array_key_exists($date, $result)) {
    $result[$date]['count']++;
    $result[$date]['total'] = bcadd($result[$date]['total'], $prices[$key], 2);
    $result[$date]['average'] = bcdiv($result[$date]['total'], $result[$date]['count'], 2);
  }
  else {
    $result[$date] = [
      'count' => 1,
      'total' => $prices[$key],
      'average' => $prices[$key]
    ];
  }
}

Note the use of the bcmath functions - it is a very bad idea to try to handle currency using floating point math.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.