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

3 Answers 3

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.

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

1 Comment

thats not bad.. anyway thanx
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

Comments

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']
     );
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.