Một lựa chọn khác sẽ là array_splice(). Điều này sắp xếp lại các phím số và dường như là một phương thức nhanh hơn nếu bạn đang thu thập đủ dữ liệu để quan tâm. Nhưng tôi thích unset() array_values () để dễ đọc.
array_splice($array, $index, $num_elements_to_remove);
http://php.net/manual/en/function.array-splice.php
thử nghiệm Tốc độ:
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
Mã kiểm tra:
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);
Nguồn
2013-02-21 19:57:02
'reset(); 'không phải là, theo PHP.net: "reset() tua lại mảng' s con trỏ nội bộ đến phần tử đầu tiên và trả về giá trị của phần tử mảng đầu tiên. " – Harmen
Ok Cảm ơn, thực sự cho downvote của bạn – streetparade