[英]Calculate age in PHP array
我想 output 在這些 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>";
}
當前 output
名稱 1
昵稱 1
07-15-1986
名稱 2
昵稱 2
07-27-1985
簡單一點:
<?
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";
}
?>
$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 // ...
這工作+ - 幾天。
$age = floor((time() - strtotime(.$players[$row][2])) / 31540000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.