PHP重置数组为连续数字索引的三种方式

PHP重置数组为连续数字索引的三种方式

比如这样的一个php数组:

$arr = array(
    1 => 'apple',
    3 => 'banana',
    5 => 'orange'
);

想要转换为这样的数组:

$arr = array(
    0 => 'apple',
    1 => 'banana',
    2 => 'orange'
);

1、推荐的方式 array_values 方法

这样方式无论对普通数组还是关联数组都适用

<?php

$arr = array(
    1 => &#39;apple&#39;,
    3 => &#39;banana&#39;,
    5 => &#39;orange&#39;
);

print_r(array_values($arr));

$arr1 = array(
    &#39;name&#39; => &#39;jerry&#39;,
    &#39;age&#39; => 16,
    &#39;height&#39; => &#39;18cm&#39;
);

print_r(array_values($arr1));

输出结果:

[root@localhost php]# php array.php 
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
Array
(
    [0] => jerry
    [1] => 16
    [2] => 18cm
)

2、使用 array_merge 方法

该方法如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。所以只能适用于数字索引

<?php

$arr = array(
    1 => &#39;apple&#39;,
    3 => &#39;banana&#39;,
    5 => &#39;orange&#39;
);

print_r(array_merge($arr));

$arr1 = array(
    &#39;name&#39; => &#39;jerry&#39;,
    &#39;age&#39; => 16,
    &#39;height&#39; => &#39;18cm&#39;
);

print_r(array_merge($arr1));

输出结果:

[root@localhost php]# php array.php 
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
Array
(
    [name] => jerry
    [age] => 16
    [height] => 18cm
)

3、循环遍历

最原始的方式,臃肿且不够优雅,极力抵制。

<?php

function resetArr($arr){
    $temp = array();
    foreach($arr as $v){
        $temp[] = $v;
    }
    return $temp;
}

$arr = array(
    1 => &#39;apple&#39;,
    3 => &#39;banana&#39;,
    5 => &#39;orange&#39;
);

print_r(resetArr($arr));

$arr1 = array(
    &#39;name&#39; => &#39;jerry&#39;,
    &#39;age&#39; => 16,
    &#39;height&#39; => &#39;18cm&#39;
);

print_r(resetArr($arr1));

That‘s it!

更多相关知识,请访问!

以上就是PHP重置数组为连续数字索引的三种方式的详细内容,更多请关注其它相关文章!