2010-04-14 4 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 –

답변

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 
관련 문제