在 DataTables $columns 数组中使用 date_diff() 函数时出现 PHP 错误

标签 php mysql arrays database datatables

请原谅,这篇文章很长。我想给出这个问题的所有背景。

我正在使用 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/

相关文章:

php - PHP 为每个数组元素赋值

c - 如何在 C 程序中声明、定义和调用函数,该函数必须具有 1 )"fill"3D 数组和 2 )"read"3D 字符数组

php - 如何使用 Google Docs for Mailer 模板?

php - Xampp 上的 Symfony 开发速度非常慢,我该怎么办?

javascript - 为什么我的 $_POST 为空,但 file_get_contents ('php://input' ) 不是?

mysql - 以单向关系表寻找共同 friend

ios - 在 Swift 中对协议(protocol)数组进行排序?

PHP require_once 包括文件但变量未在新的 httpd/php/mysql CentOS 安装上使用

MySQL 内存表已满。我怎样才能让它使用更多内存?

mysql - Codeigniter 大查询结果 result_array() result