【问题标题】:Encode/Decode Json with datetime objects symfony php使用日期时间对象 symfony php 编码/解码 Json
【发布时间】:2020-07-15 07:28:18
【问题描述】:

我有一个包含日期时间对象的数组。该数组如下所示

$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
    ]

withoutPremiumInvoiceRange 键值是一个日期时间对象。 我的问题是当我按如下方式编码这个数组时

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

并将其解码回日期时间对象如下所示

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 [▶]
  ]

我需要日期时间对象的数据。谁能帮我实现这个目标。

【问题讨论】:

    标签: php arrays json symfony decode


    【解决方案1】:

    如果没有额外的步骤,您将无法获得日期时间。您可以更改编码过程(更多信息:Change output of DateTime in json_encode),但 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'])
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-06
      • 2012-09-20
      • 2018-11-30
      • 2012-08-20
      • 1970-01-01
      • 2015-04-20
      • 2016-07-22
      • 2018-04-02
      相关资源
      最近更新 更多