gpt4 book ai didi

PHP & MySql 数组问题(非常烦人!)

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:18 25 4
gpt4 key购买 nike

作为对我正在尝试做的事情的简要说明:

我有一个包含各种列的 MySql 数据库。这些列之一是包含用户出生日期的“生日”列。

我想做的是获取此列中的所有出生日期,将它们转化为年龄,然后计算出平均年龄。

所以...我已经获得了两个部分的代码,但我无法让它们一起工作!

我可以向生日函数提供我的出生日期,它会把它变成一个年龄。

我可以将所有出生日期放入一个数组中。

我不能做的是这里的任何事情。我无法将数组转换为年龄并计算出平均值,基本上,这让我抓狂。我是 PHP 的新手,但到目前为止我已经在这方面做了很多工作。

非常感谢您的帮助以使其正常工作!我只是不知道从下面去哪里。

这是我的代码:

// Age calculation

function CalculateAge($BirthDate)
{
// Put the year, month and day in separate variables
list($Day, $Month, $Year) = explode("/", $BirthDate);

$YearDiff = date("Y") - $Year;

// If the birthday hasn't arrived yet this year, the person is one year younger
if(date("m") < $Month || (date("m") == $Month && date("d") < $DayDiff))
{
$YearDiff--;
}
return $YearDiff;
}

// How to use the function
// CalculateAge("24/06/1991");

//Birthdate array

$ages = mysql_query("SELECT birthday FROM user_records");

$agearray = array();

while($row=mysql_fetch_assoc($ages)) {array_push($agearray, $row);}

提前感谢您的帮助。

最佳答案

请记住 $row 是关联数组而不是字符串变量,因此您需要执行 $row['birthday'] 否则您会将数组对象传递给函数。我已经在下面的代码中进行了解释。

希望对你有帮助

// Age calculation

function CalculateAge($BirthDate)
{
// Put the year, month and day in separate variables
list($Day, $Month, $Year) = explode("/", $BirthDate);

$YearDiff = date("Y") - $Year;

// If the birthday hasn't arrived yet this year, the person is one year younger
if(date("m") < $Month || (date("m") == $Month && date("d") < $DayDiff))
{
$YearDiff--;
}
return $YearDiff;
}

// How to use the function
// CalculateAge("24/06/1991");

//Birthdate array

$birthdays = mysql_query("SELECT birthday FROM user_records");

$birthdaysArray = array();

while($row=mysql_fetch_assoc($birthdays)) { $birthdaysArray[] = $row['birthday']; }

//LOOP HERE TO FIND AGES

关于PHP & MySql 数组问题(非常烦人!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4821906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com