簡體   English   中英

在PHP中刪除數組項的最佳方法是什么?

[英]What is the best way to delete array item in PHP?

你能告訴我你從陣列中刪除一個項目的方法嗎? 你覺得這樣好嗎?

那要看:

$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()對於哈希表(字符串索引數組unset()是安全的,但是如果必須依賴連續數字索引,則必須使用array_splice()unset()array_values()

常用方法:

根據手冊

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 - 從數組中刪除所選項

這取決於。 如果要在不導致索引間隙的情況下刪除元素,則需要使用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"
}

使用unset可以工作,但這會導致非連續索引。 當您使用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"
}

如您所見,count現在為3,但最后一個元素的索引也是3。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM