douzhun5971 2014-11-17 11: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 11: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)'].

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部