I show orders for a period 3 months from today. If today is 17.07.2015, I show data from 17.04.2015 to 17.07.2015. My problem is that I have to show this data by weeks. In 3 months there are 12 weeks. I have to show average prices of orders for all 12 weeks.
Now, in my query, I show all orders which is in this period. But I don't have to show average_prices for all orders, have to show 12 average prices for the 12 weeks. How to do that?
<?php
public function average_price_by_week() {
$date = new DateTime("now");
$date->modify('-3 month');
$current =$date->format('Y-m-d');
$this->db->select('DATE_FORMAT(DATE_SUB(ordersheader.createdDate, INTERVAL DAYOFWEEK(ordersheader.createdDate)-2 DAY), "%Y-%m-%d") AS "interval"',FALSE);
$this->db->select_avg('unitPrice');
$this->db->from('orderitems');
$this->db->join('ordersheader', 'ordersheader.idOrder=
orderitems.idOrder');
$this->db->where('ordersheader.createdDate > ',$current);
$this->db->order_by('interval');
$this->db->group_by('interval');
$query=$this->db->get();
return $query->result_array();
My table ordersheader
has structure:
idOrder
(Primary key),idCustomer
,createdDate
,orderDueDate
My table orderitems
has structure:
id
(Primary key),idOrder
,itemNumber,
wrappingType,
size,
quantity,
unitPrice,
incomes`
One idOrder can have many orderitems.
Edited: I have to show this data in a chart. In my controller I have: How to show average price by week and interval from query instead of the array $firms to take values from the above arrays?
<?php
public function column_chart() {
$size = $this->uri->segment(3);
$interval = $this->uri->segment(4);
$firms = $this->Receivedorders_model->average_price_by_week($size,$interval);
$new_result_array=[];
$average_prices=[];
foreach($firms as $row){
if(!isset($new_result_array[date('W',strtotime($row['interval']))])){
$new_result_array[date('W',strtotime($row['interval']))]=[];
$new_result_array[date('W',strtotime($row['interval']))]['weekly_order_total']=0;
$new_result_array[date('W',strtotime($row['interval']))]['orders']=[];
}
$new_result_array[date('W',strtotime($row['interval']))]['weekly_order_total']+=$row['unitPrice'];
$new_result_array[date('W',strtotime($row['interval']))]['orders'][]=$row;
}
print_r($new_result_array);
foreach($new_result_array as $week=>$orders){
$average_prices[$week]=$orders['weekly_order_total']/count($orders['orders']);
}
print_r($average_prices);
/* How to show average price by week and interval from query in the following array -instead of $firms to take values from the above array */
$p = array();
foreach ($firms as $key => $firm) {
$p[$key] = array('c' => array(array(
'v' => $firm['interval'],
),
array(
'v' => round($firm['unitPrice'],2),
)));
}
echo json_encode(array(
'cols' => array(
array('id' => 'name', 'label' => lang("customer"), 'type' => 'string'),
array('id' => 'incomes', 'label' => lang("chart_average_price"), 'type' => 'number'),
),
'rows' => $p
));
}