dsgft1486 2014-09-25 15:17
浏览 15
已采纳

数组中元素的潜在位置和值

Array have a range of keys with it's proper values.

Let's say that array looks like this:

Array
(
    [0] => 0.00
    [2] => 0.60
    [5] => 1.00
    [1] => 0.30
    [3] => 0.90
)

So, it's without key 4.

Since array is in fact a range of elements, value of element with key 4 will be 0.90, or value of element with first lower key value.

What will be best practice to achieve, to get value 0.90 for value of 4 (that does not exist in array).

Hope that my question in not to complicated... Thank you in advance!

  • 写回答

1条回答 默认 最新

  • douan4347 2014-09-25 15:27
    关注

    I wouldn't call this a best practice, but it would give you the value you expect, that is: the value in the first entry in the array with key lower than the given one.

    function findValue( $i, $values ) 
    {
        if ( $i < 0 ) die ("Can't compute.");
    
        if ( !isset( $values[$i] ) )
        { 
            return findValue( $i-1, $values );
        }
        else
        {
            return $values[$i];
        }
    }
    
    
    $values = array(
     0 => 0.0,
     2 => 0.6,
     5 => 1.0,
     1 => 0.3,
     3 => 0.9
    );
    
    $searchedValue = findValue(4, $values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题