I would like to output the age of the person rather than the Date of birth in these arrays.
$players = array (
array("Name 1","Nickname 1","07-15-1986"),
array("Name 2","Nickname 2","07-27-1985")
);
$totalPlayers = array_sum(array_map("count", $players))/3;
for ($row = 0; $row < $totalPlayers; $row ) {
echo "<ul>";
for ($col = 0; $col < 3; $col ) {
echo "<li>".$players[$row][$col]."</li>";
}
echo "</ul>";
}
Current output
Name 1
Nickname 1
07-15-1986
Name 2
Nickname 2
07-27-1985
CodePudding user response:
A tad simpler:
<?
header("Content-type: text/plain");
$players = array (
array("Name 1","Nickname 1","07-15-1986"),
array("Name 2","Nickname 2","07-27-1978")
);
// today's date
$date1 = date_create(date("Y-m-d"));
foreach ($players as $obj)
{
// must replace "-" by "/" otherwise strtotime will assume european format dd-mm-yy
$date2 = date_create(date("Y-m-d", strtotime(str_replace("-", "/", $obj[2]))));
$interval = date_diff($date2, $date1);
echo $obj[0]." (".$obj[1].") :".$interval->format('%R%y years %m months')."\n";
}
?>
CodePudding user response:
$players = array (
array("Name 1","Nickname 1","07-15-1986"),
array("Name 2","Nickname 2","07-27-1985")
);
// Not sure why you didn't just use count...
$totalPlayers = count($players);
$now = new DateTime();
// Replace the date field in the array with the age of each player.
// Use the difference, in years, between today's date
// and the player's birthday.
$players = array_map(
function($item) use ($now) {
$item[2] =
$now->diff(
DateTime::createFromFormat('m-d-Y', $item[2])
)->y . ' years old';
return $item;
},
$players
);
for ($row = 0; $row < $totalPlayers; $row ) {
echo "<ul>";
for ($col = 0; $col < 3; $col ) {
echo "<li>".$players[$row][$col]."</li>";
}
echo "</ul>";
}
// • Name 1
// • Nickname 1
// • 36 years old
// ...
CodePudding user response:
This works - a few days.
$age = floor((time() - strtotime(.$players[$row][2])) / 31540000);