2010-04-14 5 views
3

Je dois prendre un tableau qui ressemble à ...Compresser un tableau PHP

array(11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal"); 

et le convertir en ...

array(0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal"); 

C'est ce que je suis venu avec -

function compressArray($array){ 
    if(count($array){ 
     $counter = 0; 
     $compressedArray = array(); 
     foreach($array as $cur){ 
      $compressedArray[$count] = $cur; 
      $count++; 
     } 
     return $compressedArray; 
    } else { 
     return false; 
    } 
} 

Je suis juste curieux de savoir s'il y a une fonctionnalité intégrée dans php ou des trucs soignés pour ce faire.

+0

double: http://stackoverflow.com/questions/1111761/what-is-the-built-in-php-function-for-compressing-or-defragmenting-an-array –

Répondre

10

Vous pouvez utiliser array_values

Exemple pris directement à partir du lien,

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

Sorties:

Array 
(
    [0] => XL 
    [1] => gold 
) 
3

Utilisez array_values pour obtenir un tableau des valeurs:

$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 ​​() est probablement le meilleur choix, mais comme note annexe intéressante, array_merge et array_splice vont aussi ré-indexer un tableau.

$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