我有一个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数组中插入零?
答案 0 :(得分:1)
试试这个:
$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>";