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

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?

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