本文旨在提供一种更简洁高效的方法,在 php 中基于一个数组(percentile_bounds)中元素的位置,从另一个数组(percentiles)中选择对应的值。通过结合 array_filter 和 max(array_keys()) 函数,可以避免冗长的代码,实现同样的功能,提高代码的可读性和执行效率。文章将详细介绍这种方法,并提供示例代码。
在 PHP 中,有时我们需要根据一个数组中的值在另一个数组中查找对应的值。例如,我们有两个数组,percentiles 和 percentile_bounds,以及一个整数值 total_score。我们的目标是找到 total_score 落在 percentile_bounds 的哪个区间内,然后返回 percentiles 数组中对应的值。
一种更简洁高效的 PHP 实现方式如下:
<?php $percentiles = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]; $percentile_bounds = [84, 104, 109, 115, 120, 123, 125, 127, 129, 132, 135, 136, 137, 139, 141, 145, 148, 151, 155, 159]; $total_score = 130; $index = max(array_keys(array_filter($percentile_bounds, function ($x) use ($total_score) { return $x < $total_score; }))); echo "Percentile: " . $percentiles[$index]; // 输出:Percentile: 40 ?>
代码解析:
立即学习“PHP免费学习笔记(深入)”;
-
array_filter($percentile_bounds, function ($x) use ($total_score) { return $x < $total_score; }): 此函数使用回调函数过滤 percentile_bounds 数组。回调函数接收 percentile_bounds 数组中的每个元素 $x,并检查它是否小于 total_score。只有小于 total_score 的元素才会被保留在过滤后的数组中。
-
array_keys(…): 此函数返回过滤后的数组的所有键名。由于我们只保留了小于 total_score 的元素,这些键名代表了 percentile_bounds 数组中小于 total_score 的元素的索引。
-
max(…): 此函数返回 array_keys 函数返回的键名数组中的最大值。由于 percentile_bounds 数组是排序的,因此最大键名对应于小于 total_score 的最大值的索引。
-
$percentiles[$index]: 最后,我们使用这个索引从 percentiles 数组中检索对应的值。
示例:
以下是一些使用不同 total_score 值的示例:
- total_score = 120: 输出 Percentile: 20
- total_score = 153: 输出 Percentile: 85
- total_score = 100: 输出 Percentile: 0
注意事项:
-
边界情况:如果 total_score 小于 percentile_bounds 数组中的最小值(例如,total_score <= 84),上述代码将返回 0,这符合题目中的要求。这是因为 array_filter 会返回一个空数组,array_keys 也会返回一个空数组,max 函数作用于空数组会返回 false,在 PHP 中 false 会被转换为 0。
-
数组排序: 此方法依赖于 percentile_bounds 数组的排序。如果数组未排序,则需要先对其进行排序,然后再使用此方法。
-
性能: 对于大型数组,使用 array_filter 可能会影响性能。如果性能至关重要,可以考虑使用循环来手动查找索引。
总结:
通过结合 array_filter 和 max(array_keys()) 函数,我们可以简洁高效地在 PHP 中根据一个数组的值在另一个数组中查找对应的值。这种方法比传统的循环方法更具可读性,并且通常具有更好的性能。然而,重要的是要考虑边界情况和数组排序,以确保代码的正确性。