我有一个年龄数据: 18,25,36,20,23,21,31,
使用php如何显示此类数据? 10至20年= 1人,20至30年= 4人,30至40年= 2人
答案 0 :(得分:1)
您可以尝试类似的方法。它使用array_map
将数据中的所有值除以10(从而将它们分组),然后使用array_count_values
来计算每个组中的人数。
$ages = [18,25,36,20,23,21,31];
$groups = array_count_values(array_map(function ($v) { return (int)($v / 10); }, $ages));
for ($i = 0; $i <= max(array_keys($groups)); $i++) {
echo $i*10 . " to " . ($i*10+9) . " years: " . (isset($groups[$i]) ? $groups[$i]: 0) . "\n";
}
输出:
0 to 9 years: 0
10 to 19 years: 1
20 to 29 years: 4
30 to 39 years: 2
更新
如果您不想显示其中没有人的群组,请改用以下循环:
for ($i = 0; $i <= max(array_keys($groups)); $i++) {
if (isset($groups[$i])) echo $i*10 . " to " . ($i*10+9) . " years: " . $groups[$i] . "\n";
}
输出:
10 to 19 years: 1
20 to 29 years: 4
30 to 39 years: 2
答案 1 :(得分:0)
有很多方法,但是我更喜欢直接从mysql查询中获取,
SELECT IF (`age` < 10, '0 to 10 years',
IF(`age` > 10 AND `age` < 20, '10 to 20 years',
IF(`age` > 20 AND `age` < 30, '20 to 30 years', 'more than 30 years')
)
) AS age_group,
count(*) as `counts`
FROM `table_name`
Group by `age_group`
您可以参考此answer来从数据库中存储的DOB中计算年龄
答案 2 :(得分:0)
此代码从您的数据库中收集了生日日期,并在所需范围内将它们分组。
//Please update this section to grant access to your database
$username = 'root'; //Your Database Username
$password = ''; //Your Database Password
$database = 'test_sample'; //Your Database Name
$table_name = 'ages'; //Your Table Name
$column_name = 'date_of_birth'; // The Column where the birthday dates can be accessed
$query = 'SELECT `'.$column_name.'` FROM `'.$table_name.'`';
$db_connection = mysqli_connect('localhost', $username, $password, $database);
$result = mysqli_query($db_connection, $query);
$current_ages = [];
$now = new DateTime();
while($data = mysqli_fetch_array($result)) {
$date = new DateTime($data[$column_name]);
$interval = $now->diff($date);
$current_ages[] = $interval->y;
}
// $current_ages = [18,25,36,20,23,21,31];
$desired_range = [
[10,20], [21,30], [31,40], [41,50]
];
$result = [];
foreach($current_ages as $data) {
foreach($desired_range as $index => $range) {
if($data >= $range[0] && $data <= $range[1]) {
(isset($result[$index]))? $result[$index]++ : $result[$index] = 1;
break;
}
}
}
foreach($desired_range as $index => $range) {
$count = (isset($result[$index]))? $result[$index] : 0;
echo $range[0]." to ".$range[1]." years = ".$count.' <br/>';
}
答案 3 :(得分:0)
$ages = [18,25,36,20,23,21,31];
$years = array(); // floor range
foreach ($ages as $age)
{
$m = (int)($age / 10);
(isset($years[($m*10)])) ? $years[($m*10)]++ : $years[($m*10)] = 1;
}
var_dump($years); // output: array(3) { [10]=> int(1) [20]=> int(4) [30]=> int(2) }