我这里有一个表单(https://nursinggroup.com/pharmacist-profile/),用户将在"从"输入框和"到"输入框中以"mm/yy"的形式输入日期。在用户浏览并添加所有日期之后,他们提交表单,然后使用Gravity Forms PDF Extended (mPDF)创建PDF。我需要做的是,在创建PDF的过程中,我需要它计算每个项目的值,并将每个项目的总年数输出到PDF中。
例如,如果我在在线表单中输入以下条目:
Ambulatory Care "From: 02 / 88" "To: 02 / 98"
Home Healthcare "From: 07 / 02" "To: 07 / 05"
Oncology "From: 09 / 06" "To: 05 / 12"
在PDF上,它会吐出以下内容:
Ambulatory Care 10
Home Healthcare 3
Oncology 5.8
我已经通读并尝试了许多不同的代码示例,但我只是没有足够的技能与这种类型的PHP使这个工作。还有几件事要记住。这是在一个WordPress网站上,使用Gravity Forms作为表单,并使用Gravity Forms PDF Extended从这些表单创建PDF。另外需要注意的是,年份的输入必须保持yy
而不是yyyy
的格式。用户也不填写日期,只填写mm / yy
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
我要做的是为计算的数字创建单独的字段。这样,您可以通过条目ID直接在PDF中输出它们,而不必在PDF创建过程中运行任何自定义。
要计算年数,我建议使用如下代码:
http://gravitywiz.com/calculate-number-of-days-between-two-dates/它将计算天数;但是,可以很容易地修改它来计算年数,只需更改这一行:
dayCount = diff / ( 60 * 60 * 24 * 1000 );
…:
dayCount = diff / ( 60 * 60 * 24 * 360 * 1000 );
你也可以重命名这个变量,但是你需要替换它在当前作用域中所有被引用的地方