PHP重置数组为连续数字索引的几种方式
PHP重置数组为连续数字索引的几种方式
比如这样的一个php数组:
[php] view plain copy
$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
$arr = array(
0 => 'apple',
1 => 'banana',
2 => 'orange'
);
<?php
$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
print_r(array_values($arr));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
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
)
<?php
$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
print_r(array_merge($arr));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
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
)
<?php
function resetArr($arr){
$temp = array();
foreach($arr as $v){
$temp[] = $v;
}
return $temp;
}
$arr = array(
1 => 'apple',
3 => 'banana',
5 => 'orange'
);
print_r(resetArr($arr));
$arr1 = array(
'name' => 'jerry',
'age' => 16,
'height' => '18cm'
);
print_r(resetArr($arr1));
想要转换为这样的数组:
[php] view plain copy
1、推荐的方式 array_values 方法
这样方式无论对普通数组还是关联数组都适用
[php] view plain copy
输出结果:
[sql] view plain copy
2、使用 array_merge 方法
该方法如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。所以只能适用于数字索引。
[php] view plain copy
输出结果:
[php] view plain copy
3、循环遍历
最原始的方式,臃肿且不够优雅,极力抵制。
[php] view plain copy
That‘s it!