9

配列に空の要素を持たずに、配列の要素を削除し、後で並べ替えるにはどうすればよいですか?

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

回答 / 解決策: 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
?>
4

7 に答える 7

2

別のオプションはarray_splice()です。これにより数値キーが並べ替えられ、十分なデータを処理する場合はより高速な方法のように見えます。しかし、私は読みやすさのためにunset()array_values()が好きです。

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

http://php.net/manual/en/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);
于 2013-02-21T19:57:02.263 に答える
0
$array=["one"=>1,"two"=>2,"three"=>3];
$newArray=array_shift($array);

return array_values($newArray);

[2,3] を返す array_shift 配列から最初の要素を削除する array_values 値だけを返す

于 2019-08-13T14:44:00.083 に答える
0

array_shift() は、配列の最初の値をシフトして返し、配列を 1 要素短くして、すべてを下に移動します。すべての数値配列キーはゼロからカウントを開始するように変更されますが、リテラル キーは変更されません。

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/en/function.array-shift.php

于 2017-12-18T09:34:01.190 に答える