如何将所有关键点从数组的起点和终点向前移动一个位置


How can I shift all keys one position forward from a starting and end point in an array?

所以我有一个这样的数组:

 [
        543 => 1,
        22  => 3,
        65  => 4,
        10  => 5,
        50  => 6,
    ]

现在我得到一个键和一个值作为输入。例如,22作为键,5作为值。

现在,我想在数组中使用这两个输入作为起点和终点,并希望将所有键在这两个位置之间向前移动一个。

 [
    543 => 1,
    22  => 3,  ─┐                                      ┌─  65 => 3,
    65  => 4,   ├ Shift all those keys one forward to: ┤   10  => 4,
    10  => 5,  ─┘                                      └─  22  => 5,
    50  => 6,
]

因此,预期输出为:

   [
        543 => 1,
        65 => 3,
        10 => 4,
        22=> 5,
        50  => 6,
    ]

计算出数组中输入的开始和结束偏移量:

$startIndex = array_search(22, array_keys($arr));
$endIndex   = array_search(5 , array_values($arr));
                         //↑ Your input

因此,对于您的示例数组,它看起来像这样:

[
    543 => 1,  //Offset: 0
    22  => 3,  //Offset: 1 ← 22 found; offset: 1
    65  => 4,  //Offset: 2
    10  => 5,  //Offset: 3 ←  5 found; offset: 3
    50  => 6,  //Offset: 4
]

将您的阵列拆分为三部分:

$before = array_slice($arr, 0, $startIndex, true);
$data   = array_slice($arr, $startIndex, ($endIndex - $startIndex) + 1, true);
$after  = array_slice($arr, $endIndex, null, true);

设想如下:

[
    543 => 1,  → $before; Where you do NOT want to shift your keys
    22  => 3,  ┐
    65  => 4,  ├ $data; Where you want to shift your leys
    10  => 5,  ┘
    50  => 6,  → $after; Where you do NOT want to shift your keys
]

旋转数据部分键,只需将开头的最后一个键与结尾的其他键合并即可:

$keys = array_keys($data);
$keys = array_merge(array_slice($keys, -1), array_slice($keys, 0, -1));
$data = array_combine($keys, $data);

把它们放在一起:

$arr = $before + $data + $after;