How do I format JSON date array object using PHP

how to get data from json array in php
json string to array php
php datetime format
php json date format
php read json file
php new datetime
create json array in php
php date to timestamp

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"

}

]

For some reason, the way you check for the 'date_of_birth' key causes problems. I've managed to get everything working in a foreach() loop using $value with a reference. Please try the below:

<?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 (array_key_exists('date_of_birth', $value)) {
        $oDate = DateTime::createFromFormat('Y-m-d', $value['date_of_birth']);
        $value['date_of_birth'] = $oDate->format('d-m-Y');
    }
}

file_put_contents('results_new.json', json_encode($characters));

print_r($characters);

Output:

[
  {
    "first_name": "Andy",
    "last_name": "James",
    "date_of_birth": "21-08-1988",
    "date_of_move": "2000-09-11"
  },
  {
    "first_name": "Laura",
    "last_name": "Simmons",
    "date_of_birth": "09-04-1968",
    "date_of_move": "2010-09-05"
  },
  {
    "first_name": "Jeff",
    "last_name": "Bridge",
    "date_of_birth": "15-02-1980",
    "date_of_move": "1990-08-08"
  }
]

How to decode JSON date using php?, Let's assume you did JSON parsing and got your date string $date new DateTimeZone($time[2]) : null; // Create a new date object from your First problem is the JSON date can also be in the format '/Date(1511431604000+0000​)/' , so we $json_date, $time_array); // Remove milliseconds from JSON  Array: This is defined as an ordered list of values. An array begins with a left bracket [ and ends with a right bracket ]. Values are separated by a comma ,. In JSON, keys are always strings, while the value can be a string, number, true or false, null or even an object or an array.

Try changing this line:

$oDate = DateTime::createFromFormat('Y-m-d', '1988-08-21');

With this one:

$oDate = DateTime::createFromFormat('Y-m-d', $value['date_of_birth']);

json_encode - Manual, PHP implements a superset of JSON as specified in the original » RFC 7159. echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n"; containing improperly formatted numbers array(2) { [0]=> string(13) "+a33123456789" [1]=> string(4) $arquivo = "data_".​date('ymdhis').".json"  The value of any JSON key can be a string, Boolean, number, null, array, or object. Comments are not allowed in JSON. Although JSON resembles an object or an array, JSON is a string. A serialized string, which means it can later be parsed and decoded into data types. Using data from JSON with PHP

You have to use strtotime() :

for($i=0;$i<count($characters);$i++) {
    $characters[$i]['date_of_birth'] = date("d-m-Y", strtotime($characters[$i]['date_of_birth']));
}

Here date format update to d-m-y

DateTime::format - Manual, Returns date formatted according to given format. Parameters ¶. object. Procedural style only: A DateTime object returned by date_create(). format. php,jquery,ajax,json I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON", Laravel 4.2 Sending email error

in_array($key, ['date_of_birth']) isn't working as you expect. Try this way :

$json = '[
{
    "first_name"    : "Andy",
    "last_name"     : "James",
    "date_of_birth" : "1988-08-21",
    "date_of_move"  : "2000-09-11"
},
{
    "first_name"    : "NO DATE",
    "last_name"     : "NO DATE"
},
{
    "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"

}]';

$decoded = json_decode($json);

foreach ($decoded as $key => $value)
{
    if (isset($value->date_of_birth))
    {
        $value->date_of_birth = DateTime::createFromFormat('Y-m-d', $value->date_of_birth)->format('d-m-Y');
    }
}

var_dump($decoded);

Outputs :

array (size=4)
  0 => 
    object(stdClass)[1]
      public 'first_name' => string 'Andy' (length=4)
      public 'last_name' => string 'James' (length=5)
      public 'date_of_birth' => string '21-08-1988' (length=10)
      public 'date_of_move' => string '2000-09-11' (length=10)
  1 => 
    object(stdClass)[2]
      public 'first_name' => string 'NO DATE' (length=7)
      public 'last_name' => string 'NO DATE' (length=7)
  2 => 
    object(stdClass)[3]
      public 'first_name' => string 'Laura' (length=5)
      public 'last_name' => string 'Simmons' (length=7)
      public 'date_of_birth' => string '09-04-1968' (length=10)
      public 'date_of_move' => string '2010-09-05' (length=10)
  3 => 
    object(stdClass)[4]
      public 'first_name' => string 'Jeff' (length=4)
      public 'last_name' => string 'Bridge' (length=6)
      public 'date_of_birth' => string '15-02-1980' (length=10)
      public 'date_of_move' => string '1990-08-08' (length=10)

json_decode - Manual, Date and Time Related Extensions · File System Related Extensions · Human Language and When TRUE , returned objects will be converted into associative arrays. Returns the value encoded in json in appropriate PHP type. format or even native JavaScript format, everyone who wants to use JSON wisely should  In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

How to convert PHP array to JavaScript or JSON ?, Technically, it is in JSON format. JSON stands for JavaScript Object Notation. Next, use the library function json_encode() to convert the PHP array to  JSON with PHP. This chapter covers how to encode and decode JSON objects using PHP programming language. Let's start with preparing the environment to start our programming with PHP for JSON. Environment. As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

JSON Syntax, JSON syntax is derived from JavaScript object notation syntax: Data is Data is separated by commas; Curly braces hold objects; Square brackets hold arrays  You need to pass it an array of objects. Your code currently is putting a line on each key of your single object. example: [ { Php - Convert json to csv using php not getting right format

PHP date_format() Function, PHP Date/Time Reference Return a new DateTime object, and then format the date: <?php Note: This function does not use locales (all output is in English). JSON — short for JavaScript Object Notation — is a format for sharing data. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages. This informational guide will get you up to speed

Comments
  • Legend mate. Cheers!!
  • @LeoG my pleasure! I've updated the answer with cleaned up code and removed a duplicate line.
  • @mkveksas my edit is wrong, I didn't notice the true arguments for json_decode. I rollback.
  • @Cid I tried to amend the previous edit but didn't notice you submitted a new one! Apologies.
  • Thanks for the answer. It does work but only partially. It formats the first date_of_birth, but does not format the remaining two date_of_births.
  • Are you sure? Try deleting results_new.json file and try again.