I need to format all the date_of_birth attributes of the JSON array using a PHP foreach loop.
Initial date is in Y-m-d and I need to format them to d-m-Y using PHP only.
I have tried it but maybe I am not doing something right.
<?php
// Convert json from objects to array
$characters = json_decode(file_get_contents('data.json'), true);
//Loop through array
foreach ($characters as $key => $value) {
if (in_array($key, ['date_of_birth'])) {
$oDate = DateTime::createFromFormat('Y-m-d', '1988-08-21');
$characters[$key]['date_of_birth'] = $oDate->format('d-m-Y');
}
}
file_put_contents('results_new.json', json_encode($characters));
print_r($characters);
?>
//JSON data
[
{
"first_name" : "Andy",
"last_name" : "James",
"date_of_birth" : "1988-08-21",
"date_of_move" : "2000-09-11"
},
{
"first_name" : "Laura",
"last_name" : "Simmons",
"date_of_birth" : "1968-04-09",
"date_of_move" : "2010-09-05"
},
{
"first_name" : "Jeff",
"last_name" : "Bridge",
"date_of_birth" : "1980-02-15",
"date_of_move" : "1990-08-08"
}
]