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

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案