PHP |通过重新排序从数组中删除元素?

PHP |通过重新排序从数组中删除元素?,php,arrays,pointers,return,unset,Php,Arrays,Pointers,Return,Unset,如何删除数组中的元素,然后重新排序,而数组中没有空元素? <?php $c = array( 0=>12,1=>32 ); unset($c[0]); // will distort the array. ?> 答案/解决方案:数组\u值(数组$input)。 <?php $c = array( 0=>12,1=>32 ); unset($c[0]); print_r(array_values($c)); //

如何删除数组中的元素,然后重新排序,而数组中没有空元素?

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

答案/解决方案:数组\u值(数组$input)。

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


将返回一个新数组,其中只包含线性索引的值。

如果总是删除第一个元素,请使用array_shift()而不是unset()


否则,您应该能够使用类似$a=array\u values($a)的东西。

如果只删除数组的第一项,您可以使用
array\u shift($c)

重置()
也是一个不错的选择

另一个选项是array_splice()。这种方法可以对数字键进行重新排序,如果您处理的数据足够多,那么它似乎是一种更快的方法。但我喜欢unset()数组\ u值()的可读性

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

速度测试:

    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
测试代码:

函数rutime($ru,$rus,$index){
返回($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));
}
函数时间输出($title、$rustart、$ru){
echo$title.“使用的流程”。rutime($ru,$rustart,“utime”)。
“ms用于其计算\n”;
echo$title.“已用”。rutime($ru,$rustart,“stime”)。
“系统调用中的ms\n”;
}
$test=array();
对于($i=0;$iarray_shift()将数组的第一个值移开并返回它,将数组缩短一个元素并向下移动所有内容。所有数字数组键将被修改为从零开始计数,而文字键将不被触摸

数组移位($stack)

例如:

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

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
资料来源:

返回[2,3] 数组\u shift从数组中删除第一个元素
数组_值只返回值

reset();
不是,根据PHP.net:“reset()将数组的内部指针倒回到第一个元素,并返回第一个数组元素的值。”哇,你很擅长复制和粘贴。请阅读
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
$array=["one"=>1,"two"=>2,"three"=>3];
$newArray=array_shift($array);

return array_values($newArray);