duanbi9202 2017-11-25 09:29
浏览 21
已采纳

获取数组中的前导者和后继者的数量

I have an array of objects, and I want to count the number of previous and next indexes from a given value, up to a certain maximum count.

Array
(
    [0] => stdClass Object
        (
            [id] => 460
        )

    [1] => stdClass Object
        (
            [id] => 484
        )

    [2] => stdClass Object
        (
            [id] => 485
        )

    [3] => stdClass Object
        (
            [id] => 486
        )

    [4] => stdClass Object
        (
            [id] => 489
        )

    [5] => stdClass Object
        (
            [id] => 501
        )

    [6] => stdClass Object
        (
            [id] => 654
)

Case: maximum count is 2

  • If the value is 460, the previous index count is 0 (as [0]) and the next index count is 2 (as [1] and [2])
  • If the value is 485, the previous index count is 2 (as [0] and [1]) and the next index count is 2 (as [3] and [4])
  • If the value is 501, the previous index count is 2 (as [3] and [4]) and the next index count is 1 (as [6])
  • If the value is 654, the previous index count is 2 (as [4] and [5]) and the next index count is 0 (as [6])

How can I get these two counts when an array, a value and a maximum count is given?

  • 写回答

1条回答 默认 最新

  • dongsaolian8786 2017-11-25 09:52
    关注

    It seems you want to know whether there are 2 elements before and after the element with the value you search, and if not, how many there are (0 or 1).

    Here is a function you could use:

    function getPrevNext($arr, $find, $max = 2) {
        foreach($arr as $i => $obj) {
            if ($obj->id == $find) {
                return [min($max, $i), min($max, count($arr) - 1 - $i)];
            }
        }
        return [-1, -1]; // not found
    }
    

    It will return two values (as an array), i.e. those prev and next values. If it does not find the value you are looking for, it returns -1 for both.

    Here is how you could call it:

    $arr = [ 
        (object) ["id" => 460],
        (object) ["id" => 484],
        (object) ["id" => 485],
        (object) ["id" => 486],
        (object) ["id" => 489],
        (object) ["id" => 501],
        (object) ["id" => 654],
    ];
    
    list($prev, $next) = getPrevNext($arr, 484, 2);
    
    echo "prev: $prev, next: $next"; // prev: 1, next: 2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致