boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

根据数值范围从PHP数组中查找对应值


avatar
作者 2025年8月24日 18

根据数值范围从PHP数组中查找对应值

本文将介绍如何在php中,根据一个数值(total_score)在另一个已排序的数组(percentile_bounds)中的位置,从一个数组(percentiles)中查找对应的值。通过使用array_filter和array_keys等函数,可以高效地实现此功能,并提供示例代码帮助读者理解和应用。

问题描述

假设我们有两个数组:$percentiles 和 $percentile_bounds,以及一个整数值 $total_score。$percentile_bounds 数组是已排序的,我们希望找到 $total_score 落在 $percentile_bounds 中的哪个区间,然后返回 $percentiles 数组中对应的值。

解决方案

PHP提供了一些内置函数,可以帮助我们高效地实现这个功能。以下是一种简洁的解决方案:

<?php  $total_score = 120; $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];  $index = max(array_keys(array_filter($percentile_bounds, function ($x) use ($total_score) { return $x < $total_score; })));  echo "percentile: " . $percentiles[$index]; // 输出 percentile: 15  ?>

代码解释:

立即学习PHP免费学习笔记(深入)”;

  1. array_filter($percentile_bounds, function ($x) use ($total_score) { return $x < $total_score; }): 使用 array_filter 函数过滤 $percentile_bounds 数组,只保留小于 $total_score 的元素。匿名函数 function ($x) use ($total_score) { return $x < $total_score; } 定义了过滤的条件。use ($total_score) 允许匿名函数访问外部变量 $total_score。
  2. array_keys(…): 获取经过 array_filter 过滤后的数组的键(索引)。
  3. max(…): 由于 $percentile_bounds 数组是已排序的,因此过滤后数组的最后一个键(索引)对应于小于 $total_score 的最大值在 $percentile_bounds 数组中的位置。使用 max 函数获取这个最大的键。
  4. $percentiles[$index]: 使用获取到的索引 $index,从 $percentiles 数组中获取对应的值。

示例

以下是一些使用不同 $total_score 值的示例:

  • $total_score = 130; 输出:percentile: 40
  • $total_score = 153; 输出:percentile: 85
  • $total_score = 100; 输出:percentile: 0
  • $total_score = 84; 输出:percentile: 0

注意事项

  • 边界情况: 如果 $total_score 小于 $percentile_bounds 数组中的最小值,上述代码将返回索引为 0 的值。 如果需要处理这种情况,可以在代码中添加额外的判断逻辑。例如,当 $total_score <= 84 时,返回 0。
  • 数组排序: 此解决方案依赖于 $percentile_bounds 数组是已排序的。如果数组未排序,则需要先对其进行排序。
  • 性能: 对于大型数组,可以考虑使用二分查找等更高效的算法来查找 $total_score 的位置。

总结

通过结合 array_filter、array_keys 和 max 函数,我们可以简洁高效地根据一个数值在另一个数组中的位置,从PHP数组中查找对应的值。 这种方法在处理范围查找、数据映射等场景中非常有用。



评论(已关闭)

评论已关闭