且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能在Codeigniter中使用Chart.js创建月度销售报告

更新时间:2023-02-05 15:51:05

首先,让我们澄清一点,我看到 $ kazanc_v [0] $ kazanc_v->小计总计是对象和数组吗?该变量的输出是什么?



使用这样的输出也会迫使您犯错。如果要显示每个日期的销售总数或总价,则应按日期分组从数据库中获取数据。



您在模型中的查询应该是这样;

  //在模型中
$ this-> db-> select( count(quantity)为数量,DATE(order_date)为日期)
-> from( orders)
-> where(order_date> 2021-01-01)//本月初
-> group_by('date')
-> get()
-> result_array()
;

现在,您需要创建 x轴首先。
在您的情况下,一个月中的总天数(我们认为是31天)

  //在您的控制器中
$ begin = new DateTime(date('Ym-01')); //或指定日期
$ end = new DateTime(date(’Y-m-t’));
$ end = $ end->修改( +1天);
$ interval =新的DateInterval('P1D');
$ dateRange =新的DatePeriod($ begin,$ interval,$ end);

您有一个带有日期的数组,现在可以使用带有数据的y和x轴创建图表数据

  $ chartData = []; 
$ kazanc = $ this-> some_model-> some_method();

foreach($ dateRange as $ date){
$ dataKey = array_search($ date-> format( Y-m-d),array_column($ kazanc,‘date’));
if($ dataKey!== false){//如果给定日期有数据
$ chartData [$ date-> format( Ymd)] = $ kazanc [$ dataKey] ['qty'];
} else {
//如果没有记录,则创建默认值
$ chartData [$ date-> format( Y-m-d)] = 0;
}
}

//发送数据以查看
$ this-> load-> view('template',[ chartData => $ chartData]);

现在,您有31天的日期(x轴)和数量(y轴)数据在 $ chartData 变量中。



最后,我们可以在视图中打印数据。根据chartjs文档,类似这样。

  //在您看来
var options = {
type:'line',
数据:{
标签:<?php echo json_encode(array_keys($ chartData)); ?>,
数据集:[
{
标签:#总数量,
数据:<?php echo json_encode(array_values($ chartData)); ?>,
borderWidth:1
}
]
},

示例工作代码(php) https://www.tehplayground.com/pmiPYk3yhIpExJqa



jsfiddle for chartjs。 https://jsfiddle.net/jwf67voe/


I have a chart which is created with chart.js

I get the totals on a daily basis from the database, and some days there is no earnings like this:

id | seller | date             | quantity | price | total

1    3636    2019-10-09 10:00   4           1,2      4,8
2    3045    2019-10-09 15:51   2           0,6      1,2
3    3636    2019-10-06 11:05   8           1,0      8,0
4    3636    2019-10-04 14:03   5           0,9      4,5
5    3636    2019-10-01 14:57   3           0,4      1,2

Like you see, there are 2 sales on October 9, 1 sale on October 6, 5 sales on October 4, and 1 sale on October 1.

I create a code for this but it does not work very well:

//$kazanc_v is sales dates array which is come from the controller
            for($i=1;$i<31;$i++)
            { 
                $arr2[]=date('Y').'-'.date('m').'-'.$i;
            }
            for($k=0;$k<30;$k++){
                  if(in_array($arr2[$k],$kazanc_v[0])){
                         echo $kazanc_v->sub_total;
                      } else {
                          echo '0,';
                }
             }

When I get data into data sets the chart looks like this:

for can't see img: wrong chart

I cant write '0' in charts data because there is no data in table. I want to write 0 when there is no sale on dates and chart is should be like this which I want

for can't see img : [october reports]3

How can I create real report?

First of all, lets make it clear a bit, i see $kazanc_v[0] and $kazanc_v->sub_total is this and object or array? What is the output of this variable?

Also working with such output will force you do a mistake. If you want to show total count of sales or sum price per date, you should get data from database as grouped by date.

your query in your model should be something like this;

//in your model
$this->db->select("count(quantity) as qty, DATE(order_date) as date") 
         ->from("orders")
         ->where(order_date > "2021-01-01") //beginning of this month
         ->group_by('date')
         ->get()
         ->result_array()
 ;

Now, you need to create x-axis first. In your case total day in a month (we consider as 31 days)

//in your controller
$begin = new DateTime( date('Y-m-01') ); //or given date
$end = new DateTime( date('Y-m-t') );
$end = $end->modify( '+1 day' ); 
$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($begin, $interval ,$end);

you have an array with dates, now you can create your chart data with y and x axis with data coming from your model.

$chartData =[];
$kazanc = $this->some_model->some_method();  

foreach($dateRange as $date){
  $dataKey = array_search($date->format("Y-m-d"), array_column($kazanc, 'date'));
  if ($dataKey !== false) { // if we have the data in given date
      $chartData[$date->format("Y-m-d")] = $kazanc[$dataKey]['qty'];
  }else {
      //if there is no record, create default values
     $chartData[$date->format("Y-m-d")] = 0;
  }
}

//send data to view
$this->load->view('template', ["chartData" => $chartData]);

now, you have date (x-axis) and qty (y-axis) for 31 days data in $chartData variable.

Finally, we can print our data in view. According to chartjs documentation, something like this.

// in your view
var options = {
  type: 'line',
  data: {
   labels: <?php echo json_encode(array_keys($chartData)); ?>,
   datasets: [
        {
          label: '# Total Quantity',
          data: <?php echo json_encode(array_values($chartData)); ?>,
          borderWidth: 1
        }
    ]
 },

sample working code (php) https://www.tehplayground.com/pmiPYk3yhIpExJqa

jsfiddle for chartjs. https://jsfiddle.net/jwf67voe/