原谅我,这很长。我想提供这个问题的所有背景资料。
我正在为一个项目使用DataTables服务器端处理。我的目标是利用echo函数来echo我数据库中名为createdDate的列中从今天的日期到日期之间的天数,createdDate是一种日期时间类型。
我试图先让基本功能在数据表之外工作,下面的功能按预期工作,并将$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";
 }

在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.提前谢谢!

最佳答案

只需从回调返回字符串。

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

09-11 17:39
查看更多