【问题标题】:How do i assign results of a function compute to a variable in PHP如何将函数计算的结果分配给 PHP 中的变量
【发布时间】:2014-07-16 17:58:48
【问题描述】:

我使用 laravel 的 eloquent 从数据库中收集数据。我需要将 DATETIME 值转换为时间戳。我成功地做到了,但无法将其分配回结果。它让我头疼。代码sn-p如下。

public function getArticle() {
    $article = new Article;
    $data =  $article::find(Input::get("article_id"));
    $data->created_at = $this->getTimestamp($data->created_at);
    return $data;

}

将日期时间转换为时间戳的函数如下:

public function getTimestamp($datetime) {
    $time = strtotime($datetime);
    return $time;
}

任何帮助将不胜感激

【问题讨论】:

  • "但无法将其分配回结果。" - 为什么?是什么东西或某人阻止你为此编写代码?
  • "$data->created_at = $this->getTimestamp($data->created_at);"你想在那里做什么?它只是将同一时间复制回自身?
  • 如果遇到问题,请尝试在函数调用前后使用 var_dump 输出$data->created_at,看看它是否具有您期望的值。
  • @TheShiftExchange It is just copying the same time back to itself? 它在通过函数调用后设置一个变量。
  • 是的——但是函数调用是从那个对象上已经的时间戳返回一个strtotime。所以它实际上并没有做任何有用的事情。

标签: php laravel


【解决方案1】:

Laravel Eloquent 使用Carbon。您不需要转换任何东西 - 它可以自动在结果上完成:

printf("Right now is %s", $data->created_at->toDateTimeString());

还有许多其他方法可以操纵 Carbon 选项。 You can see a full list here at the Carbon Github page.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 2011-04-03
    • 2013-11-12
    • 1970-01-01
    • 2010-10-29
    • 2020-10-05
    • 1970-01-01
    • 2022-07-02
    相关资源
    最近更新 更多