PHP&MySql数组问题(非常讨厌!)
问题描述:
作为我想要做什么的简短说明:PHP&MySql数组问题(非常讨厌!)
我有一个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
答
那么接下来,你需要遍历您的阵列和使用功能转换为年龄。
$calculated_ages = array();
foreach($agearray as $d)
{
$calculated_ages[] = CalculateAge($d);
}
然后得到平均值。
答
而不是拉入PHP,你可以从MySQL查询直接做到这一点,
例如,下面的查询返回一个用户的天数平均年龄为当前日期:
SELECT AVG(DATEDIFF(NOW(), birthday)) AS AverageAge FROM `user_records`;
答
drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null,
dob date not null
)
engine=innodb;
insert into users (username, dob) values
('f00','1960-01-01'), ('bar','1970-01-01'),
('alpha','1980-01-01'), ('beta','1990-01-01'),
('delta','2000-01-01'), ('theta','2010-01-01'),
('zeta',curdate());
select
if(sum(a.age) is null, 0, sum(a.age)) as sum_age,
count(*) as count_ages,
if(count(*) = 0, 0, sum(a.age)/count(*)) as avg_age
from
(
select
date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d')) as age
from users
) a
+---------+------------+---------+
| sum_age | count_ages | avg_age |
+---------+------------+---------+
| 156 | 7 | 22.2857 |
+---------+------------+---------+
1 row in set (0.00 sec)
+0
这是一个很好的查询:) – 2011-01-27 23:08:58
真棒家伙,谢谢,我知道这一切工作!非常感谢。 – Kieran 2011-01-27 21:46:56