2009-04-08 84 views

回答

3

這應該是更大的陣列更快。對於較小的數組,任何方法都可以。

$existingKeys = array_keys($array); 

//you can use any value instead of null 
$newKeys = array_fill_keys(range(min($existingKeys), max($existingKeys)), null); 
$array += $newKeys; 

//optional, probably not needed 
ksort($array); 
-1

如果你想要做的是重新排序陣列等你拿

Array([0] => Apple [1] => Orange [2] => Pear [3] => Pear) 

只需創建一個新的磁盤陣列和值複製到它。它會分配新的索引順序

$new_array = array(); 
for($value in $old_array) 
    $new_array[] = $value; 
+0

使用array_Values()代替for循環 – OIS 2009-04-08 08:37:51

1

你可以嘗試從最低指數爲()到最高和完整,如果它是空的

for($i = 0 ;$i <= 8 ; $i++) 
{ 
//if it's not set 
if(!isset($array[$i])) 
{ 
//set to empty 
$array[$i] = ""; 
} 

} 

此外,你可以先算陣列上元素的數量並將其包裝在一個函數中

function completeIndexes($array) 
    { 

    $total = count($array); 
    for($i = 0 ;$i < $total ; $i++) 

     { 
     //if it's not set 
     if(!isset($array[$i])) 
     { 
     //set to empty 
     $array[$i] = ""; 
     } 

     } 
return $array; 
    } 
1
for($i=0;i<count($array);++$i){ 
    $array[$i] = isset($array[$i])? $array[$i] : ''; 
} 

雖然它只是用空字符串填充丟失的鍵。不知道這是否適合你。

編輯

只注意到Perr0_hunter寫了幾乎同樣的事情,我之前做過:P