douzhun5971 2014-11-17 19:27
浏览 38
已采纳

如何读取PHP数组中的多个日期值,然后减去它们,返回一个int值

I have a task that I need to implement, in a nutshell I want to be able to read multiple date values from a table in mySQL using PHP then manipulate these values to get date difference in days, save these new days (int values) into another array for further manipulation (linear regression). My problem is I cant get to the point where I can save initial values retrieved from the DB into an array, but when I try to manipulate these values and save them into a second array, it does not work. here is my simple code:

$result = mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=1",$conn);
$num_rows = mysql_num_rows($result);
// mysql_query($result,$conn) or die(mysql_error();

//echo $num_rows;


$data = array();
$days=array();

while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
  $data[] = $row; // add the row in to the results (data) array
}

print_r($data); // print result


//This part is not working

for ($x=$num_rows;$x>0;$x--){
$days[x]=(($data[$x])-($data[$x-1]));
}
print_r($days);



mysql_close($conn);

If I don't include the for loop in my code, I get an output on the screen as follows:

Array ( 
    [0] => Array ( [TO_DAYS(date)] => 735599 ) 
    [1] => Array ( [TO_DAYS(date)] => 735630 ) 
    [2] => Array ( [TO_DAYS(date)] => 735658 ) 
    [3] => Array ( [TO_DAYS(date)] => 735689 ) 
    [4] => Array ( [TO_DAYS(date)] => 735735 ) 
    [5] => Array ( [TO_DAYS(date)] => 735780 ) 
    [6] => Array ( [TO_DAYS(date)] => 735811 )
)

Please I really need some help here. Thank You - Hamood

  • 写回答

1条回答 默认 最新

  • duancan7914 2014-11-17 19:45
    关注

    Try this:

    for ($x = $num_rows - 1; $x > 0; $x--) {
        $days[$x] = $data[$x]['TO_DAYS(date)'] - $data[$x-1]['TO_DAYS(date)'];
    }
    

    Here, $data[$x] is an array itself with key TO_DAYS(date), so you need to get your desired value with $data[$x]['TO_DAYS(date)'].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题