我在数组上遇到了一些麻烦。我有一个数组,我想修改如下。我想通过索引删除它的元素(元素),然后重新索引数组。这可能吗?
$foo = array(
'whatever', // [0]
'foo', // [1]
'bar' // [2]
);
$foo2 = array(
'foo', // [0], before [1]
'bar' // [1], before [2]
);
我在数组上遇到了一些麻烦。我有一个数组,我想修改如下。我想通过索引删除它的元素(元素),然后重新索引数组。这可能吗?
$foo = array(
'whatever', // [0]
'foo', // [1]
'bar' // [2]
);
$foo2 = array(
'foo', // [0], before [1]
'bar' // [1], before [2]
);
当前回答
一段时间后,我将复制所有数组元素(不包括这些不需要的)到新数组
其他回答
PHP 7.4的2020基准测试
对于那些对目前的答案不满意的人,我做了一个小的基准测试脚本,任何人都可以从CLI运行。
我们将比较两种解决方案:
unset()与array_values() VS array_splice()。
<?php
echo 'php v' . phpversion() . "\n";
$itemsOne = [];
$itemsTwo = [];
// populate items array with 100k random strings
for ($i = 0; $i < 100000; $i++) {
$itemsOne[] = $itemsTwo[] = sha1(uniqid(true));
}
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
unset($itemsOne[$i]);
$itemsOne = array_values($itemsOne);
}
$end = microtime(true);
echo 'unset & array_values: ' . ($end - $start) . 's' . "\n";
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
array_splice($itemsTwo, $i, 1);
}
$end = microtime(true);
echo 'array_splice: ' . ($end - $start) . 's' . "\n";
正如你所看到的,这个想法很简单:
创建两个具有相同100k项的数组(随机生成的字符串) 使用unset()和array_values()从第一个数组中删除10k个第一个项来重新索引 使用array_splice()从第二个数组中删除10k个第一项 两种方法都要测量时间
在我的戴尔Latitude i7-6600U 2.60GHz x 4和15.5GiB RAM上输出上面的脚本:
php v7.4.8
unset & array_values: 29.089932918549s
array_splice: 17.94264793396s
结论:array_splice的性能几乎是unset和array_values的两倍。
所以:array_splice是赢家!
unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
array_splice($array, 0, 1);
http://php.net/manual/en/function.array-splice.php
试一试:
$foo2 = array_slice($foo, 1);
array_splice($array, array_search(array_value, $array), 1);