简体   繁体   中英

Calculate average age of members (PHP)

I want to create the average age of my members. I already managed to get an array of all the date of births and found an easy way to calculate a birthday. But I don't manage to combine it.

My 'date of birth' - array:

$results = array();

$dob_array = mysqli_query($conn, "SELECT dob_array FROM members");

    while($row = mysqli_fetch_assoc($dob_array)){
        $results[] = $row;
    }

The calculation of the age:

$today = new DateTime();
$birthdate = new DateTime("1991-01-01");
$interval = $today->diff($birthdate);
echo $interval->format('%y years');

Calculation average of my age-array:

$average = array_sum($array) / count($array);

可以使用直接sql(使用TIMESTAMPDIFF()AVG()函数)完成:

SELECT AVG(TIMESTAMPDIFF(YEAR, `dob`, NOW())) as `average` FROM `member`;

这可能是一个:

SELECT AVG(DOB_COLUMN_NAME) from TABLE NAME

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM