用于“压缩”或“碎片整理”数组的内置PHP函数是什么?

时间:2022-01-04 14:08:36

I know it'd be trivial to code myself, but in the interest of not having more code to maintain if it's built in to PHP already, is there a built-in function for "compressing" a PHP array? In other words, let's say I create an array thus:

我知道自己编写代码是微不足道的,但是如果它已经内置到PHP中而没有更多的代码来维护,是否有一个用于“压缩”PHP数组的内置函数?换句话说,假设我创建了一个数组:

$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;

What I want is an array where $array[0] == 5, $array[1] == 7, $array[2] == 9.

我想要的是一个数组,其中$ array [0] == 5,$ array [1] == 7,$ array [2] == 9。

I could do this:

我能做到这一点:

function array_defragment($array) {
    $squashed_array = array();
    foreach ($array as $item) {
        $squashed_array[] = $item;
    }
    return $squashed_array;
}

...but it seems like the kind of thing that would be built in to PHP - I just can't find it in the docs.

...但它似乎是PHP内置的东西 - 我只是在文档中找不到它。

1 个解决方案

#1


Just use array_values:

只需使用array_values:

$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;

$array = array_values($array);
var_dump($array === array(5, 7, 9));

#1


Just use array_values:

只需使用array_values:

$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;

$array = array_values($array);
var_dump($array === array(5, 7, 9));