需求描述: 前端发送请求如33-55岁,后端拿到年龄数据后将指定年龄转为日期
$search = $_POST;
$year = date('Y');
$month = date('m');
$day = date('d');
$max_birth = '';
$min_birth = '';
// 用户输入了最小年龄和最大年龄
if(isset($search['person_age_min']) && isset($search['person_age_max'])){
$min = min($search['person_age_min'], $search['person_age_max']);
$max = max($search['person_age_min'], $search['person_age_max']);
# 计算最大年龄的最早出生日期
$max_year = $year - $max - 1;
$max_birth = date('Y-m-d', strtotime("+1 day", strtotime($max_year.'-'.$month.'-'.$day)));
# 计算最小年龄的最后出生日期
$min_year = $year-$min;
$min_birth = $min_year.'-'.$month.'-'.$day;
}elseif(isset($search['person_age_min']) && !isset($search['person_age_max'])){ //用户只输入了最小年龄
# 计算最大年龄的最早出生日期
$max_year = $year - $search['person_age_min'] - 1;
$max_birth = date('Y-m-d', strtotime("+1 day", strtotime($max_year.'-'.$month.'-'.$day)));
# 计算最小年龄的最后出生日期
$min_year = $year-$search['person_age_min'];
$min_birth = $min_year.'-'.$month.'-'.$day;
}elseif(!isset($search['person_age_min']) && isset($search['person_age_max'])) { // 用户只输入了最大年龄
# 计算最大年龄的最早出生日期
$max_year = $year - $search['person_age_max'] - 1;
$max_birth = date('Y-m-d', strtotime("+1 day", strtotime($max_year.'-'.$month.'-'.$day)));
# 计算最小年龄的最后出生日期
$min_year = $year-$search['person_age_min'];
$min_birth = $min_year.'-'.$month.'-'.$day;
}
if(!empty($min_birth) && !empty($max_birth)){
// sql语句
$sql = "select * from user where birth between $max_birth and $min_birth";
}