Search code examples
phpsqlarraysarray-map

Ignore duplicate values in PHP - MYSQL using Arraymap


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


Solution

  • 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.