我正在尝试计算学生的年龄,我已将他们的值存储在数组中,如下所示:
$day = array(30, 03);
$month = array(07, 12);
$year = array(1998, 1997);
我想计算他们当前的年龄和以下结果。那么,我怎样才能计算出他们在阵列中的年龄。
$age = array(18, 19);
答案 0 :(得分:3)
您可以使用array_map
并使用封闭内的DateTime::diff
返回差异。
$day = array(30, 03);
$month = array(07, 12);
$year = array(1998, 1997);
$now = new DateTime();
$age = array_map(function($year, $month, $date) use ($now) {
return (new DateTime($year . '-' . $month . '-' . $date))->diff($now)->y;
}, $year, $month, $day);
答案 1 :(得分:0)
我假设所有三个数组都有相同的数:
$age=[];
for($i=0;$i<count($day);$i++)
{
$date= $day[$i]."-".$month[$i]."-".$year[$i];
$from = new DateTime($date);
$to = new DateTime('today');
$diff = $from->diff($to)->y;
array_push($age,$diff);
}
print_r($age);
答案 2 :(得分:0)
解决方案:
$day = array(30, 03, 23);
$month = array(07, 12, 03);
$year = array(1998, 1997, 1987);
$age = [];
$now = new DateTime('today');
for ($i = 0; $i < count($day); $i++) {
$d = $day[$i];
$m = $month[$i];
$y = $year[$i];
// Create DateTime object
$birthdate = new DateTime($y.'-'.$m.'-'.$d);
// Calculate difference between birthdate and now and get years
$age[$i] = $birthdate->diff($now)->y;
}
print_r($age);
答案 3 :(得分:-1)
<?php
$day = array(30, 03);
$month = array(07, 12);
$year = array(1998, 1997);
$arrAges = array();
$todayTime = new DateTime();
foreach($year as $ikey=>$y){
$birthDate = $y . '-' . $month[$ikey] . '-' . $day[$ikey];
$bdTime = new DateTime($birthDate);
$ageInterval = $todayTime->diff($bdTime);
$arrAges[] = $ageInterval->y;
}
var_dump($arrAges);