
本文介绍了如何在PHP中,根据一个整数值在另一个数组中的位置,从一个数组中选择对应的元素。通过结合array_filter、array_keys和max函数,可以高效地实现此功能,并提供代码示例进行演示。同时,也考虑了边界情况,确保代码的健壮性。
在PHP中,有时需要根据一个数组(例如,percentile_bounds)中元素与给定值(例如,total_score)的关系,从另一个数组(例如,percentiles)中选择相应的元素。以下方法提供了一种简洁高效的解决方案。
假设我们有两个数组:
我们的目标是,给定一个$total_score,找到$percentile_bounds中小于$total_score的最大值对应的索引,并使用该索引从$percentiles中获取相应的值。
立即学习“PHP免费学习笔记(深入)”;
以下PHP代码片段展示了如何实现这一目标:
<?php
$total_score = 130;
$percentile_bounds = [84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137, 139, 141, 145, 148, 151, 155, 159];
$percentiles = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95];
$filtered_bounds = array_filter($percentile_bounds, function ($x) use ($total_score) {
return $x < $total_score;
});
$keys = array_keys($filtered_bounds);
$last_index = max($keys);
$percentile = $percentiles[$last_index];
echo "Percentile: " . $percentile . PHP_EOL; // 输出 Percentile: 40
?>这段代码首先使用array_filter函数过滤$percentile_bounds数组,只保留小于$total_score的元素。然后,使用array_keys获取过滤后数组的键(索引)。由于$percentile_bounds是排序的,我们可以使用max函数找到最后一个键(索引),该索引对应于小于$total_score的最大值。最后,使用该索引从$percentiles数组中检索相应的值。
如果$total_score小于或等于$percentile_bounds中的最小值(例如,84),那么array_filter将返回一个空数组,array_keys也会返回一个空数组,max函数会返回false。 在这种情况下,访问$percentiles[false] 会导致PHP将false强制转换为0,从而返回$percentiles[0],这在某些情况下可能是期望的结果(如题目描述中所述,total_score<=84时结果应为0)。如果需要更严格的处理,可以添加额外的条件检查:
<?php
$total_score = 80; // Example: total_score less than the minimum bound
$percentile_bounds = [84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137, 139, 141, 145, 148, 151, 155, 159];
$percentiles = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95];
$filtered_bounds = array_filter($percentile_bounds, function ($x) use ($total_score) {
return $x < $total_score;
});
$keys = array_keys($filtered_bounds);
if (empty($keys)) {
$percentile = 0; // Or handle the case as needed, e.g., return null or throw an exception
} else {
$last_index = max($keys);
$percentile = $percentiles[$last_index];
}
echo "Percentile: " . $percentile . PHP_EOL; // 输出 Percentile: 0
?>通过结合array_filter、array_keys和max函数,我们可以有效地从一个数组中选择元素,基于另一个数组中与给定值的比较结果。 此外,处理边界情况确保代码的健壮性和可靠性。 这种方法简洁明了,易于理解和维护。
以上就是根据另一数组的值从PHP数组中选择元素的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号