简体   繁体   English

使用日期时间对象 symfony php 编码/解码 Json

[英]Encode/Decode Json with datetime objects symfony php

I have a array with datetime objects.The array lookks like as follows我有一个包含日期时间对象的数组。该数组如下所示

$advanceresult= array:68 [▼
      "contact" => array:1 [▶]
      "policyBranch" => ArrayCollection {#38322 ▶}
      "assuranceContact" => ArrayCollection {#38337 ▶}
      "info" => null
      "withSurplusShare" => false
      "withSurpassedSurplusShare" => false
      "withoutPremiumInvoice" => false
      "withoutPremiumInvoiceRange" => array:2 [▼
        "start" => DateTime @1577833200 {#38339 ▶}
        "end" => DateTime @1609369200 {#38346 ▶}
      ]
      "showPoliciesFromArchivedContacts" => false
    ]

The withoutPremiumInvoiceRange key value is a datetime object. withoutPremiumInvoiceRange 键值是日期时间 object。 My problem is when i encode this array as follows我的问题是当我按如下方式编码这个数组时

$advanceresultencode=json_encode($advanceresult);
json_decode($advanceresultencode, true);

and decode it back the datetime objects is looking like as follows并将其解码回日期时间对象如下所示

enter code here

"withoutPremiumInvoiceRange" => array:2 [▼
    "start" => array:3 [▼
      "date" => "2020-01-01 00:00:00.000000"
      "timezone_type" => 3
      "timezone" => "Europe/Zurich"
    ]
    "end" => array:3 [▶]
  ]

I need the data to datetime object.Can anyone help me acheiving this.我需要日期时间 object 的数据。谁能帮我实现这一点。

You can't have the datetime without an extra step.如果没有额外的步骤,您将无法获得日期时间。 You can change the encode process (more info here: Change output of DateTime in json_encode ) but same issue on json_decode.您可以更改编码过程(更多信息在这里: Change output of DateTime in json_encode )但在 json_decode 上有同样的问题。

Here is what you can do on json_decode:以下是您可以对 json_decode 执行的操作:

<?php

// Here your json as string
$json = ...;

$jsonDecoded = json_decode($json);

$jsonDecoded['withoutPremiumInvoiceRange']['start'] = DateTime::createFromFormat(
    'Y-m-d H:i:s.u', 
    $jsonDecoded['withoutPremiumInvoiceRange']['start']['date'], 
    new DateTimeZone($jsonDecoded['withoutPremiumInvoiceRange']['start']['timezone'])
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM