我有一个数字数组,这是一个无序列表: -
$a = array(
'0' => '2',
'1' => '4',
'2' => '6'
'3' => '8'
'4' => '10'
);
在这里,如果我想搜索数字8,那么应该返回 指数值= 3 ,但是如果我想获得不在数组中的值3那么它应该返回最接近的值
like 4= index value '1' and 2 =index value '0'.
如何在php
中找到此索引值?
答案 0 :(得分:2)
<?php
function array_search_closest($needle, $haystack)
{
$closest = null;
foreach( $haystack AS $key => $value )
{
if( $closest === null || abs($needle - $value) < $closest[0] )
$closest = [abs($needle - $value), $key];
}
return $closest[1];
}
$array = [6,2,10,4,8];
echo array_search_closest(3, $array); //Output: 1
该逻辑的基本功能是找到针与阵列中每个项目之间的最低绝对值。该值存储在$closest
数组中。
第一次迭代总是设置绝对值(我们需要检查一些东西)。之后,如果$closest
与当前迭代值之间的绝对值低于上次迭代的绝对值,则仅覆盖$needle
。我们最终获得了我们想要的最低价值。
我们最终会返回该值的关键字。
请注意$closest
实际上是一个数组。第一个元素表示当前最接近的$haystack
值,而最后一个元素是您想要的键。
答案 1 :(得分:1)
执行此操作的简单方法如下:
function closest($array, $val) {
$b=array_map(create_function('$v', 'return abs($v-'.$val.');'), $array);
asort($b);
return key($b);
}
echo closest(8); // returns 3
答案 2 :(得分:-1)
你可以像这样获取foreach循环中的键和值,
foreach($a as $key=>$value)