arrays - Encode/Decode Json with datetime objects symfony php
Get the solution ↓↓↓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. 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.
Answer
Solution:
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.
Here is what you can do on 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'])
);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: dompdf image not found or type unknown
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.