Sanjay Kumar
Sanjay Kumar

Reputation: 424

Show array data according to month

I have array like below.The array data may vary from Jan to Dec for each product

Array
(
[0] => Array
    (
        [0] => Array
            (
                [SalesYear] => 2018
                [SalesMonth] => July
                [TotalSales] => 1
                [name] => Budweiser Beer 330ml (Pack of 3)
                [code] => BB330
            )

        [1] => Array
            (
                [SalesYear] => 2018
                [SalesMonth] => August
                [TotalSales] => 2
                [name] => Budweiser Beer 330ml (Pack of 3)
                [code] => BB330
            )

        [2] => Array
            (
                [SalesYear] => 2018
                [SalesMonth] => September
                [TotalSales] => 16
                [name] => Budweiser Beer 330ml (Pack of 3)
                [code] => BB330
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [SalesYear] => 2018
                [SalesMonth] => August
                [TotalSales] => 11
                [name] => Chicharon 100g
                [code] => CC100
            )

        [1] => Array
            (
                [SalesYear] => 2018
                [SalesMonth] => September
                [TotalSales] => 3
                [name] => Chicharon 100g
                [code] => CC100
            )

    )

Now i want to show each month sale of product :

https://prnt.sc/kysxur

So far this is what I tried

enter image description here

Thanks

Upvotes: 1

Views: 70

Answers (2)

Evgeniy Belov
Evgeniy Belov

Reputation: 358

$result = [];
$months = [];
foreach($array as $items) {
   foreach($items as $item) {
       $months[$item['SalesMonth']] = $item['SalesMonth'];
       $result[$item['name']][$item['SalesMonth']] = ($result[$item['name']][$item['SalesMonth']]??0) + $item['TotalSales'];
    }
}
?>
<table>
<tr>
<th>Product</th>
   <?php foreach($months as $month):?>
      <th><?=$month;?></th>
   <?php endforeach;?>
</tr>
<?php foreach($result as $name => $items):?>
    <tr>
       <td><?=$name;?></td>
       <?php foreach($months as $month):?>
           <td><?=$items[$month]??0;?></td>
       <?php endforeach;?>
    </tr>
<?php endforeach;?>
</table>

Upvotes: 1

Dato DT
Dato DT

Reputation: 129

you will need uksort function but you will need to arrange some things there:

uksort($array, function($a1, $a2) {
        $time1 = strtotime($a1);
        $time2 = strtotime($a2);

        return $time1 - $time2;
    });

print_r($ar);

and months should be in string

Upvotes: 0

Related Questions