I was wondering how I could use PHP to calculate one's age given a date string with values from a JSON array:
{
"DOB":{ // should I use integers or strings for these values? I'm assuming strings for now.
"year": "1970",
"month": "01",
"day": "01"
}
}
How would I then use PHP to calculate the age?
Additionally, say all of this information is a small part of something like a staff directory, with the format of { "People":{ "user1":{ label: value },"user2":{ label: value} } }
. How could I use PHP to create <label>
tags for label within <li>
tags for value (<li><label>label</label>value</li>
) within unordered lists for each user within divs for each user?
Please tell me if this is confusing; and the calculation of the age is my highest priority right now.
Not sure if I correctly understood what you're trying to do with the user so let me know if i was mistaken:
<?php
$people = json_decode($data);
?>
<html>
<head>
<title>Users List</title>
</head>
<body>
<?php foreach ($people as $userName => $userInfo): ?>
<div>
<p><?php echo $userName; ?>
<ul>
<?php foreach ($userInfo as $label => $value): ?>
<li><label><?php echo $label; ?></label> <?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</body>
</html>
Something like this:
<?php
$str = '{"DOB":{"year": "1970","month": "01","day": "01"}}';
$obj = json_decode($str);
$obj->DOB->year = intval($obj->DOB->year);
$obj->DOB->month = intval($obj->DOB->month);
$obj->DOB->day = intval($obj->DOB->day);
$yearD = date("Y") - $obj->DOB->year;
$monthD = date("m") - $obj->DOB->month;
$dayD = date("d") - $obj->DOB->day;
if ($dayD < 0 || $monthD < 0)
$yearD--;
echo "<pre>";
echo $yearD;
echo "</pre>";
?>
Didnt take leap years into account. Just calculate no. of leap years, and add as many days.
And about your second question, you could visit this: Convert JSON to HTML Tree
Im assuming you are going to use this:
http://php.net/manual/en/function.json-decode.php
convert it to an array php can use.
<?php
$arr = json_decode('{"DOB":{"year": "1970", "month": "01", "day": "01"}}');
$year = $arr->DOB->year;
$month = $arr->DOB->month;
$day = $arr->DOB->day;
$today = date("Y-m-d");
$bday = date("Y-m-d",mktime(0, 0, 0, $month, $day, $year));
$today = new DateTime($today);
$bday = new DateTime($bday);
$age = $today->diff($bday)->y;
echo $age;
?>
This should work in PHP 5.3+ i believe.