PHP | 删除数组元素并重新排序?

9

如何删除一个数组元素并重新排序,而不在数组中留下空元素?

<?php
   $c = array( 0=>12,1=>32 );
   unset($c[0]); // will distort the array.
?>

答案/解决方案:使用 array_values函数(array $input),将数组重新索引并返回所有值。

<?php
   $c = array( 0=>12,1=>32 );
   unset($c[0]);
   print_r(array_values($c));
   // will print: the array cleared
?>
7个回答

16
array_values($c)

将返回一个只包含值的新数组,按线性方式索引。


4

如果你经常需要移除第一个元素,那么使用array_shift()而不是unset()。

否则,你可以尝试使用类似$a = array_values($a)的方法。


2

另一种选择是使用array_splice()。它重新排序数字键,如果你在处理足够的数据时会更快。但我更喜欢使用unset()和array_values()来提高可读性。

array_splice( $array, $index, $num_elements_to_remove);

http://php.net/manual/zh/function.array-splice.php

速度测试:

    ArraySplice process used 7468 ms for its computations
    ArraySplice spent 918 ms in system calls
    UnsetReorder process used 9963 ms for its computations
    UnsetReorder spent 31 ms in system calls

测试代码:

function rutime($ru, $rus, $index) {
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

function time_output($title, $rustart, $ru) {
        echo $title . " process used " . rutime($ru, $rustart, "utime") .
            " ms for its computations\n";
        echo $title . " spent " . rutime($ru, $rustart, "stime") .
            " ms in system calls\n";
}

$test = array();
for($i = 0; $i<100000; $i++){
        $test[$i] = $i;
}

$rustart = getrusage();
for ($i = 0; $i<1000; $i++){
        array_splice($test,90000,1);
}
$ru = getrusage();
time_output('ArraySplice', $rustart, $ru);

unset($test);
$test = array();
for($i = 0; $i<100000; $i++){
        $test[$i] = $i;
}

$rustart = getrusage();
for ($i = 0; $i<1000; $i++){
        unset($test[90000]);
        $test = array_values($test);
}
$ru = getrusage();
time_output('UnsetReorder', $rustart, $ru);

1

如果你只想移除数组的第一个项目,可以使用 array_shift($c);


0

array_shift()函数将数组的第一个值移除并返回它,同时将数组长度减少一个元素,并将所有元素下移。所有数字键名都将被修改为从零开始计数,而文字键名则不会受到影响。

例如:array_shift($stack);

示例:

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);

输出:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

来源:http://php.net/manual/zh/function.array-shift.php


哇,你很喜欢复制和粘贴。请阅读http://stackoverflow.com/help/how-to-answer。 - Jay Blanchard

0
$array=["one"=>1,"two"=>2,"three"=>3];
$newArray=array_shift($array);

return array_values($newArray);

返回 [2,3] array_shift 从数组中删除第一个元素 array_values 返回值


-1

或者使用 reset(); 也是一个不错的选择


根据PHP.net的解释,"reset() 重置数组的内部指针到第一个元素并返回第一个元素的值。" - Harmen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接