2010-04-14 137 views
3

我需要一個數組,看起來像......壓縮PHP數組

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

重複:http://stackoverflow.com/questions/1111761/what-is-the-built-in-php-function-for-compressing-or-defragmenting-an-array – 2010-04-14 15:35:05

回答

10

您可以使用直接從鏈接採取array_values

例,

<?php 
$array = array("size" => "XL", "color" => "gold"); 
print_r(array_values($array)); 
?> 

輸出:

Array 
(
    [0] => XL 
    [1] => gold 
) 
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) 
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