Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在sql表中不存在日期时在php数组中存储零_Php_Mysql - Fatal编程技术网

在sql表中不存在日期时在php数组中存储零

在sql表中不存在日期时在php数组中存储零,php,mysql,Php,Mysql,我有一个sql表,如下所示:- date sales 2017-04-01 230 2017-04-02 120 2017-04-03 81 2017-04-04 911 2017-04-05 90 2017-04-06 11 2017-04-09 9 2017-04-10 140 2017-04-11 90 可以看出,2017-04-07和2017-04-08没有数据。 以下是查询和php数组:- $sql="select sales from sales_data

我有一个sql表,如下所示:-

date    sales
2017-04-01  230
2017-04-02  120
2017-04-03  81
2017-04-04  911
2017-04-05  90
2017-04-06  11
2017-04-09  9
2017-04-10  140
2017-04-11  90
可以看出,2017-04-07和2017-04-08没有数据。 以下是查询和php数组:-

$sql="select sales from sales_data where date >= '2017-04-03'";
$RS=mysql_query($sql);

while(($row =  mysql_fetch_assoc($RS))) {
    $sales_val[] = $row['sales'];
}
代码运行良好,但是我想存储一个零,以防sql表中不存在日期。在这种情况下,如果日期不存在,是否可以在php数组中插入零

试试这个:

$sql="select `date`,`sales` from `sales_data` where `date` >= '2017-04-03' ORDER BY `date`";
$qrslt = mysqli_query($db,$sql);


$min_date = '9999-99-99';
$max_date = '0000-00-00';
$sales_val = array();
while(($row =  mysqli_fetch_assoc($qrslt))) {
    $sales_val[substr($row['date'],0,10)] = $row['sales'];
    $min_date = date('Y-m-d',strtotime($row['date'])) < $min_date ? date('Y-m-d',strtotime($row['date'])) : $min_date;
    $max_date = date('Y-m-d',strtotime($row['date'])) >= $max_date ? date('Y-m-d',strtotime($row['date'])) : $max_date;
}

$sd = new DateTime($min_date);
$ed = new DateTime($max_date);
$num_days = date_diff($sd,$ed)->days;
$rslts = array();
$cnt = 0;

for($d = 0;$d <= $num_days;$d++) {
    $dt = strtotime('+'.$d.' day',strtotime($min_date));
    $dts = date('Y-m-d',$dt);
    $rslts[$dts] = isset($sales_val[$dts]) ? $sales_val[$dts] : 0;
    $cnt++;
}

echo "<p>\$rslts:<pre>".print_r($rslts,true)."</pre></p>";
$sql=“从“销售”数据中选择“日期”,其中“日期”>=“2017-04-03”按“日期”排序的订单”;
$qrslt=mysqli_查询($db,$sql);
$min_date='9999-99-99';
$max_date='0000-00-00';
$sales_val=array();
而(($row=mysqli_fetch_assoc($qrslt))){
$sales_val[substr($row['date'],0,10)]=$row['sales'];
$min_date=日期($Y-m-d',STROTIME($row['date'))<$min_date?日期($Y-m-d',STROTIME($row['date')):$min_日期;
$max_date=date('Y-m-d',strottime($row['date'])>=$max_date?date('Y-m-d',strottime($row['date']):$max_date;
}
$sd=新日期时间($min_日期);
$ed=新日期时间($max_date);
$num_days=日期差异($sd,$ed)->天;
$rslts=array();
$cnt=0;

对于($d=0;$d),我可能不使用上面评论中给出的链接,而是使用MySQL数据库中的日历表。只是为了展示另一种方法:一般来说,搜索表达式是:
MySQL填补日期范围的空白。
。有很多问题都有解决方案。