PHP中基于入职年份和部门优先级筛选关联数组的实现方法
完整实现代码
function instructors(...$arrays) { // 定义部门优先级,顺序从高到低 $deptPriority = ['math', 'science', 'social']; // 步骤1:提取所有入职年份,找到最大值 $allHiredYears = array_column($arrays, 'hired'); $latestYear = max($allHiredYears); // 步骤2:筛选所有最新年份入职的员工 $latestStaff = array_filter($arrays, function($item) use ($latestYear) { return $item['hired'] == $latestYear; }); $latestStaff = array_values($latestStaff); // 步骤3:仅1个最新入职员工直接返回 if (count($latestStaff) === 1) { return $latestStaff[0]; } // 步骤4:多个最新入职员工按部门优先级筛选 foreach ($deptPriority as $dept) { $matched = array_filter($latestStaff, function($item) use ($dept) { return $item['department'] === $dept; }); $matched = array_values($matched); if (!empty($matched)) { return count($matched) === 1 ? $matched[0] : $matched; } } // 兜底:无匹配优先级部门时返回所有最新入职员工 return $latestStaff; }
调用&测试
测试场景1:仅1个最新入职员工
$arrayOne = array ( "name" => 'john', "position" => 'instructor', "hired" => '2010', "department" => 'math', ); $arrayTwo = array ( "name" => 'smith', "position" => 'instructor', "hired" => '2010', "department" => 'science', ); $arrayThree = array ( "name" => 'dave', "position" => 'instructor', "hired" => '2009', "department" => 'math', ); $arrayFour = array ( "name" => 'dave', "position" => 'instructor', "hired" => '2011', "department" => 'math', ); var_dump(instructors($arrayOne, $arrayTwo, $arrayThree, $arrayFour)); // 输出结果为$arrayFour,符合预期
测试场景2:多个最新入职员工按部门筛选
$arrayOne = array ( "name" => 'john', "position" => 'instructor', "hired" => '2010', "department" => 'math', ); $arrayTwo = array ( "name" => 'smith', "position" => 'instructor', "hired" => '2010', "department" => 'science', ); $arrayThree = array ( "name" => 'dave', "position" => 'instructor', "hired" => '2010', "department" => 'math', ); $arrayFour = array ( "name" => 'dave', "position" => 'instructor', "hired" => '2010', "department" => 'social', ); var_dump(instructors($arrayOne, $arrayTwo, $arrayThree, $arrayFour)); // 输出结果为包含$arrayOne和$arrayThree的数组,符合预期
逻辑说明
- 用
array_column快速提取所有入职年份,调用max直接拿到最大值,避免手动循环对比 - 筛选出最新入职员工后先判断数量,符合条件直接返回,不需要走部门判断逻辑
- 部门筛选严格按照预设优先级顺序遍历,找到第一个有匹配员工的部门就返回结果,完全符合需求规则
- 增加兜底逻辑,若所有最新入职员工的部门都不在预设优先级列表里,直接返回所有最新入职员工,避免返回空值
内容的提问来源于stack exchange,提问作者Rain Man
相关产品推荐
相关产品推荐

