2009-11-17 36 views

回答

8

這取決於:

$a1 = array('a' => 1, 'b' => 2, 'c' => 3); 
unset($a1['b']); 
// array('a' => 1, 'c' => 3) 

$a2 = array(1, 2, 3); 
unset($a2[1]); 
// array(0 => 1, 2 => 3) 
// note the missing index 1 

// solution 1 for numeric arrays 
$a3 = array(1, 2, 3); 
array_splice($a3, 1, 1); 
// array(0 => 1, 1 => 3) 
// index is now continous 

// solution 2 for numeric arrays 
$a4 = array(1, 2, 3); 
unset($a4[1]); 
$a4 = array_values($a4); 
// array(0 => 1, 1 => 3) 
// index is now continous 

一般unset()是哈希表(字符串索引的數組)的安全,但如果你要依靠連續的數字指標,你將不得不使用任何array_splice()unset()組合和array_values()

+1

爲什麼要使用unset與array_values結合使用而不是array_splice? – John 2009-11-19 09:21:41

+4

@John:我想到的一種情況是,當你想從一個數組中刪除多個項目。使用'unset()' - 你可以刪除這些值而不必考慮改變鍵 - 如果你已經完成了,你可以通過'array_values()'運行數組來標準化索引。這比使用'array_splice()'多次更乾淨更快。 – 2009-11-19 14:15:11

9

的常用方法:

按照manual

unset($arr[5]); // This removes the element from the array 

的過濾方式:

也有array_filter()功能照顧濾波陣列

$numeric_data = array_filter($data, "is_numeric"); 

爲了得到一個順序索引可以使用

$numeric_data = array_values($numeric_data); 

參考
PHP – Delete selected items from an array

+0

彼得,謝謝。 – lovespring 2009-11-17 17:05:45

5

這要看情況。如果希望在不索引造成的差距,除去一個元素,你需要使用array_splice:

$a = array('a','b','c', 'd'); 
array_splice($a, 2, 1); 
var_dump($a); 

輸出:

array(3) { 
    [0]=> 
    string(1) "a" 
    [1]=> 
    string(1) "b" 
    [2]=> 
    string(1) "d" 
} 

使用未設置可以工作,但是這將導致非連續索引。這有時可能是一個問題,當你使用count($ A)迭代這個數組 - 1作爲上限的量度:

$a = array('a','b','c', 'd'); 
unset($a[2]); 
var_dump($a); 

輸出:

array(3) { 
    [0]=> 
    string(1) "a" 
    [1]=> 
    string(1) "b" 
    [3]=> 
    string(1) "d" 
} 

正如所看到的,計數現在是3,但最後一個元素的索引也是3.

因此,我的建議是使用array_splice用於具有數字索引的數組,並且僅對非數字索引的數組(真正的字典)使用unset。

+0

或者你可以調用'unset($ a [2]); $ a = array_values($ a);' – nickf 2009-11-17 11:01:11

相關問題