2011-11-20 106 views
9

我有一個4值的數組。我想刪除第二個位置的值,然後讓其餘的鍵向下移動一個。如何使用php刪除數組中的特定鍵?

$b = array(123,456,789,123); 

之前在第二位置卸下鍵:

陣列([0] => 123 [1] => 456 [2] => 789 [3] => 123)

後,我想的剩餘鍵下移一個填補缺失的關鍵

陣列([0] => 123 [1] => 789 [2] =>的空間123)

我試過在特定的鍵上使用unset(),但它不會按下其餘的鍵。如何使用PHP刪除數組中的特定鍵?

+0

的[從由密鑰數組中刪除線]可能重複(HTTP://計算器.com/questions/1782041/remove-line-by-array-by-key) – hakre

回答

6

您需要array_values($b)爲了重新鍵入數組,所以鍵是順序和數字(從0開始)。

下應該做的伎倆:

$b = array(123,456,789,123); 
unset($b[1]); 
$b = array_values($b); 
echo "<pre>"; print_r($b); 
+0

+1:只需添加一個檢查:'array_key_exists',如果你曾經打算做這個動態的:) – Nonym

2

使用array_splice()

array_splice($b, 1, 1); 
// $b == Array ([0] => 123 [1] => 789 [2] => 123) 
0

如果你想在特定的位置從陣列中刪除一個項目,你可以得到該位置上的鍵,然後取消它:

$b = array(123,456,789,123); 
$p = 2; 
$a = array_keys($b); 
if ($p < 0 || $p >= count($a)) 
{ 
    throw new RuntimeException(sprintf('Position %d does not exists.', $p)); 
} 
$k = $a[$p-1]; 
unset($b[$k]); 

這適用於任何PHP數組,而不管索引開始或者字符串用於鍵。

如果要重新編號數組只需使用array_values

$b = array_values($b); 

,這將給你一個從零開始,數字索引數組。

如果原來的數組是從零開始的,數字索引的陣列,以及(在你的問題),你可以跳過部分如何獲得關鍵:

$b = array(123,456,789,123); 
$p = 2; 
if ($p < 0 || $p >= count($b)) 
{ 
    throw new RuntimeException(sprintf('Position %d does not exists.', $p)); 
} 
unset($b[$p-1]); 
$b = array_values($b); 

或者直接使用array_splice與交易偏移,而不是鍵重新索引陣列(在輸入數字鍵不保留):

$b = array(123,456,789,123); 
$p = 2; 
if ($p < 0 || $p >= count($b)) 
{ 
    throw new RuntimeException(sprintf('Position %d does not exists.', $p)); 
} 
array_splice($b, $p-1, 1); 
1

沒有人提供了一個方法與array_diff_key(),所以我將爲了保持完整性。

代碼:

var_export(array_values(array_diff_key($b,[1=>'']))); 

輸出:

array (
    0 => 123, 
    1 => 789, 
    2 => 123, 
) 

這種方法不僅提供了一個班輪預期的結果,它是安全沒有array_key_exists()條件使用。

該方法還提供了允許通過鍵在一個步驟中刪除多個元素的附加特徵。 JJJ的解決方案也允許這樣做,但只適用於連續的元素。無論其在陣列中的位置如何,都可以靈活地移除鍵。

代碼以除去第二和第四元件(鍵1和3):

var_export(array_values(array_diff_key($b,[1=>'',3=>'']))); 

輸出:

array (
    0 => 123, 
    1 => 789, 
) 
相關問題