php - 在php中修改json数组的日期格式

标签 php json

我的问题是我有数组如何包含日期时间格式的值,但我想用 Y-m-d 格式修改此值。我在这里尝试了很多问题,但是当我编码我的 json 时没有任何效果。

现在我有了:

[contacts] => Array (
                    [0] => Array (
                     [createdAt] =>2020-01-29T17:00:04.159+01:00
                   )
)

我会这样

[contacts] => Array (
                    [0] => Array (
                     [createdAt] =>2020-01-29
                   )
)

我的 php 代码是:

$contacts=$result[contacts];
foreach ($contacts as $contact) {

$time = new DateTime($contact['createdAt']);
$date = $time->format('Y-m-d');
echo '<br>' .$date; //that show the date format I want
}
//that don't show correct format
 $json=json_encode($contacts);
 print_r($json); 

有人可以帮助我吗?

最佳答案

您可以使用 reference 修改您的 $contact 数组&:

foreach ($contacts as &$contact) {

    $time = new DateTime($contact['createdAt']);
    $contact['createdAt'] = $time->format('Y-m-d'); 
}

Example

关于php - 在php中修改json数组的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59982246/

相关文章:

php - 警告 : Bad Message Return Path (PHP)

javascript - AJAX JQuery POST 不工作

javascript - 使用 jQuery 在 PHP 中获取 JSON 响应

java - 动态创建 JSON 对象

javascript - JS : How to change the value of an object's property according to that object attribute

php - 使用 PHP 数组或 JSON 的用途

javascript - 来自 Node JS 中查询 SELECT Mongoose 的 JSON 解析错误

ruby-on-rails - JSONB 不适用于 Rails 5? JSON 字段以字符串形式返回

php - 优化我的表现

php - mysql PHP 自动递增列