Skip to content

CSV for order Porduct Colleciton

I am getting orders for last week 7 days order and I am getting all product which was placed last week. Below is my code:

foreach ($orders as $order) {
    foreach ($order->getAllVisibleItems() as $item) {
        $data['sku'] = $item->getSku();
        $data['name'] = $item->getName();
        $data['price'] = $item->getPrice();
        $data['qty'] = $item->getQtyOrdered();
        $data['created_at'] = $order->getCreatedAt();
        $stream->writeCsv($data);

    }
}

and its generate csv perfectly I need some more complex things in my code.

Currently, if the same sku product is placed by 2 different customers its shows separate rows but I want if the same sku is placed more than 1 time it shows in the same row and qty multiplied and price added. And one more thing, if product A price today is 36 and its changed to 45 the next day then it should be separate how I can do that?

For e.g
Expected result:

If product A place by 2 customer and one customer place 1 qty and 2nd customer place 3qty.

So when its generate csv it will show A product in single row, qty 4 and price x 4.

And if product A price today is 36 and its changed to 45 the next day then it should be separate.

Actual result:

its showing 2 records with product A.