模型cmda里有个身份证字段sfzhm
我在前台想通用身份证号码来统计有多少八十岁以上的老人,前台标签
<?php
$data = [];
{module module=cmda}
$data[] = {$t.sfzhm};
{/module}
function countOverEighty($data) {
$count = 0;
foreach ($data as $idCardNumber) {
$birthYear = substr($idCardNumber, 6, 4);
$currentYear = date('Y');
$age = $currentYear - $birthYear;
if ($age >= 80) {
$count++;
}
}
return $count;
}
echo countOverEighty($data);
?>这样输出报错,查阅论坛,找不到方法,请求帮助。
$data = []; {module module=cmda} $data[] = {$t.sfzhm}; {/module} 你这样写会遍历全表不划算,耗时比较严重了开发建议,你在入库的时候,做一个出生日期字段,可以从身份证中提取出来,将出生日期做条件查询,比你这种全表对比快的多<script src="{HOME_THEME_PATH}static/js/echarts541.min.js"></script> <div id="main" style="width: 600px;height:400px;"></div> <script> // 身份证号码数组 const idCards = [ {module module=cmda return=sfz} '{$sfz.sfzhm}', {/module} ]; // 计算年龄 function calculateAge(idCard) { const birthDate = idCard.substring(6, 14); // 提取出生日期 const birthYear = parseInt(birthDate.substring(0, 4), 10); const birthMonth = parseInt(birthDate.substring(4, 6), 10); const birthDay = parseInt(birthDate.substring(6, 8), 10); const currentDate = new Date(); const currentYear = currentDate.getFullYear(); const currentMonth = currentDate.getMonth() + 1; // 注意月份是从0开始的 const currentDay = currentDate.getDate(); let age = currentYear - birthYear; if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) { age--; } return age; } // 获取年龄数组 const ages = idCards.map(idCard => calculateAge(idCard)); // 统计不同年龄段的人数 function countAgeGroups(ages) { const ageGroups = { '29岁以下': 0, '30-39岁': 0, '40-49岁': 0, '50-79岁': 0, '80岁以上': 0 }; ages.forEach(age => { if (age <= 29) ageGroups['29岁以下']++; else if (age >= 30 && age <= 39) ageGroups['30-39岁']++; else if (age >= 40 && age <= 49) ageGroups['40-49岁']++; else if (age >= 50 && age <= 79) ageGroups['50-79岁']++; else if (age >= 80) ageGroups['80岁以上']++; }); return ageGroups; } const ageGroupCounts = countAgeGroups(ages); // 总人口数 const totalPopulation = 1341; // 计算百分比 const ageGroupPercentages = Object.entries(ageGroupCounts).map(([group, count]) => ({ group, count, percentage: (count / totalPopulation * 100).toFixed(2) })); // 初始化 ECharts 实例 const chartDom = document.getElementById('main'); const myChart = echarts.init(chartDom); // 配置图表 const option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: params => { const { group, count, percentage } = params[0].data; return `${group}: ${count}人 (${percentage}%)`; } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', data: ageGroupPercentages.map(item => item.group), axisTick: { alignWithLabel: true } }, yAxis: { type: 'value' }, series: [{ name: '人数', type: 'bar', barWidth: '60%', data: ageGroupPercentages.map(item => ({ value: item.count, name: item.group, percentage: item.percentage })) }] }; // 使用配置项和数据显示图表 myChart.setOption(option); </script>最后用这个搞定了,谢谢老大的指导。