doufan3408 2017-04-27 05:20
浏览 14
已采纳

当sql表中没有日期时,在php数组中存储零[重复]

This question already has an answer here:

I have a sql table which looks like this :-

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

As it can be seen that for 2017-04-07 and 2017-04-08 there is no data. Following is query and php array :-

$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'];
}

The code works fine, however I want to store a zero in case the date is not present in the sql table. Is it possible to insert zero in the php array in this case where the date is not present ?

</div>
  • 写回答

1条回答 默认 最新

  • douqiao1983 2017-04-27 08:21
    关注

    Try this:

    $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>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来