Вычисление возрастов пользователей из массива в foreach - PullRequest
0 голосов
/ 26 сентября 2019

Я пытаюсь рассчитать возраст пользователей на основе дат рождения в массиве, но не получаю вывод с нужным мне foreach.

//User dates of birth
$userDob = array("1995-07-27", "1985-07-27", "1975-07-27", "1965-07-27", "1955-07-27"); 
//Create a DateTime object using the user's date of birth.
$dob = new DateTime($userDob);
//Compare the user's date of birth with today's date.
$now = new DateTime();
//Calculate the time difference between the two dates.
$difference = $now->diff($dob);
//Get the difference in years
$age = $difference->y;

//Display all ages
foreach($age as $ages)

    {
         echo $ages;
    }

1 Ответ

1 голос
/ 26 сентября 2019

Вы не можете назначить $userDob DateTime.Вы должны использовать его в вашем цикле.

//User dates of birth
$userDob = array("1995-07-27", "1985-07-27", "1975-07-27", "1965-07-27", "1955-07-27"); 

//Compare the user's date of birth with today's date.
$now = new DateTime();

//Display all ages
foreach($userDob as $date)
{
      //Create a DateTime object using the user's date of birth.
      $dob = new DateTime($date);

      //Calculate the time difference between the two dates.
      $difference = $now->diff($dob);

      //Get the difference in years
      echo $difference->y; //echo $age
}

EDIT

Лучше возвращать новый массив возрастов, чем эхо в этом цикле.А также я предлагаю использовать его как функцию с параметром для многократного использования.

function GetAges($user_ages)
{
    $ages = [];

    $now = new DateTime();

    foreach($user_ages as $date)
    {
          $dob = new DateTime($date);
          $difference = $now->diff($dob);
          $ages[] = $difference->y;
    }

    return $ages;
}

, а затем использовать

$user_ages = ["1995-07-27", "1985-07-27", "1975-07-27", "1965-07-27", "1955-07-27"];

foreach(GetAges($user_ages) as $age)
{
   echo $age . PHP_EOL;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...