在PHP中删除数组项的最佳方法是什么?

lov*_*ing 12 php arrays

你能告诉我你从阵列中删除一个项目的方法吗?你觉得这样好吗?

Ste*_*rig 14

那要看:

$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
Run Code Online (Sandbox Code Playgroud)

一般unset()是哈希表(字符串索引的数组)的安全,但如果你要依靠连续的数字指标,你就可以选择使用array_splice()或组合unset()array_values().

  • @John:我想到的一个场景是,当你想从一个数组中删除多个项目时.使用`unset()`-way,您可以删除值而无需考虑更改键 - 如果您已完成,则通过`array_values()`运行数组以规范化索引.这比使用`array_splice()`几次更干净,更快. (6认同)

Pet*_*ist 10

常用方法:

根据手册

unset($arr[5]); // This removes the element from the array
Run Code Online (Sandbox Code Playgroud)

过滤方式:

还有array_filter()函数来处理过滤数组

$numeric_data = array_filter($data, "is_numeric");
Run Code Online (Sandbox Code Playgroud)

要获得顺序索引,您可以使用

$numeric_data = array_values($numeric_data);
Run Code Online (Sandbox Code Playgroud)

参考
PHP - 从数组中删除所选项


Joh*_*ohn 6

这取决于.如果要在不导致索引间隙的情况下删除元素,则需要使用array_splice:

$a = array('a','b','c', 'd');
array_splice($a, 2, 1);
var_dump($a);
Run Code Online (Sandbox Code Playgroud)

输出:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
}
Run Code Online (Sandbox Code Playgroud)

使用unset可以工作,但这会导致非连续索引.当您使用count($ a) - 1作为上限的度量迭代数组时,这有时可能是一个问题:

$a = array('a','b','c', 'd');
unset($a[2]);
var_dump($a);
Run Code Online (Sandbox Code Playgroud)

输出:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [3]=>
  string(1) "d"
}
Run Code Online (Sandbox Code Playgroud)

如您所见,count现在为3,但最后一个元素的索引也是3.

因此,我的建议是将array_splice用于具有数字索引的数组,并且仅对具有非数字索引的数组(字典实际上)使用unset.