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)'].

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试