我需要一个看起来像......的数组
array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
并将其转换为...
array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");
这就是我提出的 -
function compressArray($array){
if(count($array){
$counter = 0;
$compressedArray = array();
foreach($array as $cur){
$compressedArray[$count] = $cur;
$count++;
}
return $compressedArray;
} else {
return false;
}
}
我只是好奇是否有任何内置功能在PHP或整洁的技巧来做到这一点。
答案 0 :(得分:11)
您可以使用array_values
直接从链接中获取的示例
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
输出:
Array
(
[0] => XL
[1] => gold
)
答案 1 :(得分:3)
使用array_values
获取值的数组:
$input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
$expectedOutput = array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");
var_dump(array_values($input) === $expectedOutput); // bool(true)
答案 2 :(得分:1)
array_values()可能是最好的选择,但作为一个有趣的附注,array_merge和array_splice也将重新索引数组。
$input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
$reindexed = array_merge($input);
//OR
$reindexed = array_splice($input,0); //note: empties $input
//OR, if you do't want to reassign to a new variable:
array_splice($input,count($input)); //reindexes $input