
本文将介绍如何在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免费学习笔记(深入)”;
以下是一些使用不同 $total_score 值的示例:
通过结合 array_filter、array_keys 和 max 函数,我们可以简洁高效地根据一个数值在另一个数组中的位置,从PHP数组中查找对应的值。 这种方法在处理范围查找、数据映射等场景中非常有用。
以上就是根据数值范围从PHP数组中查找对应值的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号