【问题标题】:PHP error when using date_diff() function within DataTables $columns array在 DataTables $columns 数组中使用 date_diff() 函数时出现 PHP 错误
【发布时间】:2016-12-24 13:34:25
【问题描述】:

请原谅,这篇文章有点长。我想提供这个问题的所有背景。

我正在为一个项目使用DataTables 服务器端处理。我的目标是利用echo 函数来echo 我的数据库中名为 CreatedDate 的列中的日期和日期之间的天数,该列是 DateTime 类型。

我试图让基本功能首先在 DataTables 之外工作,下面的函数按预期工作,并输出$date$date 之间的天数 $current_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";
 }

在我的 DataTables $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.

我该如何解决这个问题?我很难在 DataTables 数组中获取 $created_date$date 变量的 var_dump() 来查看问题所在。

有关DataTables服务器端处理的更多信息,I am using this template as a base for my DataTables script.DataTables脚本也使用this helper class.提前谢谢!

【问题讨论】:

    标签: php mysql arrays database datatables


    【解决方案1】:

    只需从回调中返回您的字符串。

    '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
         }
    

    【讨论】:

    • 谢谢!为什么我需要return 而不是echo
    • 闭包必须返回一些东西,所以在 'datatable.com' 代码深处的某个地方,它将基于它启动一些对象。由于我们通常需要一个结果,所以很难在没有返回的情况下成像关闭:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2020-03-06
    相关资源
    最近更新 更多