0

DB

Date        Price  qty
2012-10-21  $11 150
2012-10-22  $12 90
2012-10-22  $12 10
2012-10-23  $13 250

CODE

$result = mysqli_query($con, "SELECT * FROM table ORDER BY 'date'");

    while ($row = mysqli_fetch_array($result)) {
        $orders[] = array(
            'Date' => $row['date'],
            'price' => $row['price'],
            'Quantity' => $row['qty']
        );
    }

I don't need to get duplicate dates and for those duplicate dates need to get Average price and sum of Qty like below example:

EXAMPLE

Date        Price  qty
2012-10-21  $11 150
2012-10-22  $12 100
2012-10-23  $13 250

I try to use Array-map but i fail on that help is really appreciated

Amal Prasad
  • 157
  • 1
  • 4
  • 14

3 Answers3

2

I'd suggest to move the problem to the database by using this query using GROUP BY and the respective aggregation functions:

SELECT `date`, AVG( `price` ), SUM( `qty`)
FROM `table`
GROUP BY `date`
ORDER BY `date`

In general, it is more advisable to let MySQL do such work, than first transmitting the data to your application and rearrange it there.

Sirko
  • 72,589
  • 19
  • 149
  • 183
0

Change you query

SELECT Date, AVG(Price), SUM(Qty) FROM table
GROUP BY Date

Or change php to check if date in array and calculate averages and sums

unconnected
  • 991
  • 1
  • 10
  • 21
0

Can you try this,

   $result = mysqli_query($con, "SELECT date, AVG(Price) as price, SUM(qty) FROM table GROUP BY date ORDER BY date");

   while ($row = mysqli_fetch_array($result)) {
    $orders[] = array(
        'Date' => $row['date'],
        'price' => $row['price'],
        'Quantity' => $row['qty']
     );
   }
Krish R
  • 22,583
  • 7
  • 50
  • 59