Bir php dizi sıkıştırmak

3 Cevap php

Ben şöyle bir dizi almak gerekir ...

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

ve onu dönüştürmek ...

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

Bu ben ile geldi budur -

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

Bunu yapmak için php veya düzgün hileler herhangi yerleşik işlevselliği varsa ben sadece merak ediyorum.

3 Cevap

array_values ​​() muhtemelen en iyi seçimdir, ama ilginç bir yan not, array_merge ve array_splice de olacak re-index bir dizi olarak.

$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