删除元素并重新索引


Remove element and reindex

逻辑是在特定间隔后从元素中获取最后一个元素,当所有元素都被移除时。 假设有五个用户,每个 secound 用户都被淘汰,那么我必须找到剩下的最后一个用户。

$foo = array(
    '0'=>'1',
    '1'=>'2',
    '2'=>'3',
    '3'=>'4',
    '4'=>'5',
    '5'=>'6'
);

现在删除索引为 2 的元素,并按以下格式重新索引数组。

$foo = array(
    '0'=>'4',
    '1'=>'5',
    '2'=>'6',
    '3'=>'1',
    '4'=>'2',
);
您可以使用

unset() ,但您还需要调用 array_values() 来强制重新索引。例如:

unset($foo[2]);
$foo = array_values($foo);

最初的问题有点不清楚。我知道您想删除索引 X,并将索引 X 之后的所有项目作为数组中的第一个项目。

$index2remove = 2;
$newArray1 = array_slice($foo, $index2remove+1); // Get items after the selected index
$newArray2 = array_slice($foo, 0, $index2remove); // get everything before the selected index
$newArray = array_merge($newArray1, $newArray2); // and combine them

或者更短,内存消耗更少(但更难阅读):

$index2remove = 2;
$newArray = array_merge(
                array_slice($foo, $index2remove+1),  // add last items first
                array_slice($foo, 0, $index2remove) // add first items last
             );

您不需要在我的代码中取消设置值 2,只需将其切出即可。我们使用第二个拼接函数中的 -1 来做到这一点。

如果需要,您可以将$newArray = array_merge()替换为 $foo = array_merge() ,但仅在不需要保存原始数组的情况下在第二个替换。

编辑:更改了小错误,谢谢简平原

试试这个,输出如下

    $foo = array('0'=>'1','1'=>'2','2'=>'3','3'=>'4','4'=>'5','5'=>'6');
    //need to input this as the index of the element to be removed
    $remove_index = "2";
    unset($foo[$remove_index]);
    $slice1 = array_slice($foo, 0, $remove_index);
    $slice2 = array_slice($foo, $remove_index);
    $final_output = array_merge($slice2, $slice1);

输出

  Array
(
    [0] => 4
    [1] => 5
    [2] => 6
    [3] => 1
    [4] => 2
 )