请原谅,这篇文章很长。我想给出这个问题的所有背景。
我正在使用 DataTables项目的服务器端处理。我的目标是利用 echo
功能echo
今天的日期和我的数据库中名为 CreatedDate 的列中的日期之间的天数,这是一种 DateTime 类型。
我试图让基本功能首先在 DataTables 之外工作,下面的函数按预期工作,并输出 $current_date
$date
之间的天数和 $date
如:“16 天直播”、“15 天直播”等:
$sql = "SELECT CreatedDate FROM Estimates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$created_date = $row["CreatedDate"];
$date = new DateTime($created_date);
$current_date = new DateTime();
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
} else {
echo "No results";
}
在我的数据表中 $columns
数组,我试图达到同样的效果:
// date variable
$created_date = 'CreatedDate';
$current_date = new DateTime();
// array of database columns which should be read and sent back to DataTables.
// the 'db' parameter represents the column name in the database, while the 'dt'
// parameter represents the DataTables column identifier.
$columns = array(
array( 'db' => 'Client', 'dt' => 0 ),
array( 'db' => 'EstimateNumber', 'dt' => 1 ),
array( 'db' => 'Status', 'dt' => 2 ),
array( 'db' => 'CurrentEstimateTotal', 'dt' => 3 ),
array(
'db' => $created_date,
'dt' => 4,
'formatter' =>
function ($created_date, $row) use ($current_date) {
$date = new DateTime($created_date);
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
)
);
我一直收到以下错误:
PHP Notice: Trying to get property of non-object.
我该如何解决这个问题?我很难获得 $created_date
的 var_dump()和 $date
DataTables 数组中的变量以查看问题所在。
有关 DataTables 服务器端处理的更多信息,I am using this template as a base for my DataTables script. DataTables 脚本还使用 this helper class.提前致谢!
最佳答案
只需从回调中返回您的字符串。
'formatter' =>
function ($created_date, $row) use ($current_date) {
$date = new DateTime($created_date);
$diff = date_diff($date, $current_date);
return $diff->format('%d days live'); //That will solve your problem
}
关于在 DataTables $columns 数组中使用 date_diff() 函数时出现 PHP 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004325/