题
有没有一种简单的方法可以使用 PHP 从数组中删除元素,例如 foreach ($array)
不再包含该元素?
我以为将其设置为 null
会这样做,但显然它不起作用。
解决方案
删除数组元素的方法有多种,其中某些方法对于某些特定任务比其他方法更有用。
删除一个数组元素
如果你只想删除一个数组元素,你可以使用 \unset()
或者替代地 \array_splice()
.
另外,如果您有该值但不知道删除该元素的键,您可以使用 \array_search()
拿到钥匙。
\unset()
方法
请注意,当您使用 \unset()
数组键不会更改/重新索引。如果你想重新索引你可以使用的键 \array_values()
后 \unset()
它将所有键转换为从 0 开始的数字枚举键。
代码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\unset($array[1]);
//↑ Key which you want to delete
?>
输出
[
[0] => a
[2] => c
]
\array_splice()
方法
如果你使用 \array_splice()
键将自动重新索引,但关联键不会改变,而不是 \array_values()
这会将所有键转换为数字键。
还 \array_splice()
需要偏移量,而不是密钥!作为第二个参数。
代码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
//↑ Offset which you want to delete
?>
输出
[
[0] => a
[1] => c
]
array_splice()
与...一样 \unset()
通过引用获取数组,这意味着您不想将这些函数的返回值分配回数组。
删除多个数组元素
如果你想删除多个数组元素并且不想调用 \unset()
或者 \array_splice()
您可以多次使用这些功能 \array_diff()
或者 \array_diff_key()
取决于您是否知道要删除的元素的值或键。
\array_diff()
方法
如果您知道要删除的数组元素的值,那么您可以使用 \array_diff()
. 。和以前一样 \unset()
它不会更改/重新索引数组的键。
代码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff($array, ["a", "c"]);
//└────────┘→ Array values which you want to delete
?>
输出
[
[1] => b
]
\array_diff_key()
方法
如果您知道要删除的元素的键,那么您想使用 \array_diff_key()
. 。在这里,您必须确保将键作为第二个参数中的键而不是作为值传递。否则,你必须翻转数组 \array_flip()
. 。而且这里的键不会更改/重新索引。
代码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
//↑ ↑ Array keys which you want to delete
?>
输出
[
[1] => b
]
另外如果你想使用 \unset()
或者 \array_splice()
要删除具有相同值的多个元素,您可以使用 \array_keys()
获取特定值的所有键,然后删除所有元素。
其他提示
应当指出的是 unset()
将保持索引不变,这是您在使用字符串索引(数组作为哈希表)时所期望的,但在处理整数索引数组时可能会非常令人惊讶:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
所以 array_splice()
如果您想规范化您的整数键,可以使用。另一种选择是使用 array_values()
后 unset()
:
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
这是从上面的代码的输出:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
现在,array_values()将很好地重新索引的数值阵列,但它会从数组中删除所有密钥串和用数字替换它们。如果您需要保存键值名(串),或重新索引数组,如果所有的键是数值,使用array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
输出
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
unset($array[$index]);
如果你有一个数字索引阵列,其中所有的值是唯一的(或者它们是不唯一的,但要删除一个特定的值的所有实例),则可以简单地使用和array_diff()来除去的匹配元件,像这样:
$my_array = array_diff($my_array, array('Value_to_remove'));
例如:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
此显示以下内容:
4
3
在这个例子中,具有值“查尔斯”在元件作为能够通过的sizeof进行验证()调用,对所述初始报告阵列尺寸为4,和后取出3。除去
此外,对于名为元素:
unset($array["elementName"]);
<强>消灭的阵列的单个元件强>
<强> unset()
强>
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
的输出将是:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
如果您需要重新索引数组:
$array1 = array_values($array1);
var_dump($array1);
然后输出将是:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
<强>弹出元件关阵列的端强> - 返回被删除的元素的值
<强> mixed array_pop(array &$array)
强>
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
的输出将是
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
<强>从阵列删除所述第一元件(红色), - 返回被删除的元素的值
<强> mixed array_shift ( array &$array )
强>
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
的输出将是:
Array
(
[b] => green
[c] => blue
)
First Color: red
<?php
$stack = array("fruit1", "fruit2", "fruit3", "fruit4");
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
输出:
Array
(
[0] => fruit2
[1] => fruit3
[2] => fruit4
)
fruit1
要避免这样做的搜索可以玩弄array_diff
:
$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11
在这种情况下,一个不必搜索/使用该密钥。
如果您要删除阵列中的多个值和数组中的条目是对象或结构化数据,[array_filter][1]
是你最好的选择。从回调函数返回一个真正的条目将被保留。
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]
unset()
破坏指定的变量。
unset()
的函数内的行为可取决于正在试图破坏的变量的类型而变化。
如果一个全球化变量的函数的内部unset()
,只是局部变量被破坏。在主叫环境变量将保持unset()
被称为前的值相同。
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
上面的代码的答案将是的栏强>
要unset()
的函数的内部的全局变量:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
关联数组
有关关联数组,使用的 unset
强> :
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
数字阵列
有关数字数组,使用的 array_splice
强> 一个>:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
注意
使用的 unset
强> 为数字阵列将不会产生错误,但它会弄乱你的索引:
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)
如果需要从关联数组中删除多个元素,可以使用 array_diff_key() (这里与 数组翻转()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
输出:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
假设有以下数组:
Array
(
[user_id] => 193
[storage] => 5
)
要删除storage
,做到:
unset($attributes['storage']);
$attributes = array_filter($attributes);
和你:
Array
(
[user_id] => 193
)
我只想说我有具有可变属性(它基本上映射表,我被改变所述表中的列,所以在对象的属性,反映了表将变化以及特定对象):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
$fields
的全部目的只是,这样我就不必到处看看代码时,他们改变了,我只是看在类的开头和更改属性的列表,并在 $领域强>阵列内容,以反映新的属性。
请的默认功能:
i)个
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
ⅱ)
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
ⅲ)
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
IV)
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
<强>解决方案:强>
- 要删除一个元件,使用未设置(): 醇>
- 要删除多个不连续的元件,还使用未设置(): 醇>
- 要删除多个连续元素,使用 array_splice(): 醇>
unset($array[3]); unset($array['foo']);
unset($array[3], $array[5]); unset($array['foo'], $array['bar']);
array_splice($array, $offset, $length);
<强>的进一步说明:强>
使用这些函数删除从PHP这些元件的所有参考文献。如果要保持在阵列中的一个关键的,但具有空值,则空字符串指定给元素:
$array[3] = $array['foo'] = '';
此外语法,还有使用未设置()和之间的逻辑差分配“”的元素。第一称This doesn't exist anymore,
而第二说This still exists, but its value is the empty string.
如果你正在处理的数字,分配0可能是一个更好的选择。所以,如果一个公司停止生产的型号XL1000链轮,它将与更新其库存:
unset($products['XL1000']);
但是,如果暂时跑出XL1000链轮,但正计划在本周晚些时候收到从植物新货,这是更好的:
$products['XL1000'] = 0;
如果您未设置()的元件,PHP调整阵列以便该循环仍在正常工作。它不压缩的阵列来填充缺失的漏洞。这就是我们的意思,当我们说所有的数组是关联的,即使他们看起来是数字。下面是一个例子:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
要压缩阵列成致密地填充数值数组,使用 array_values() :
$animals = array_values($animals);
可替换地, array_splice()自动重新索引阵列以避免留下孔:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
这如果你使用数组作为队列,并希望从队列中删除的项目,同时还允许随机访问是非常有用的。安全地从数组中删除第一或最后一个元素,使用 array_shift()一>和 array_pop()时,分别
未设置()倍数,从数组元素零散
虽然unset()
这里已经几次提到,但它尚未提及的是unset()
接受多个变量使其易于删除数组多个非连续的元件在一个操作:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
未设置()动态地
未设置()不接受键除去的阵列,所以下面的代码将失败(它将使它略微更容易使用未设置()动态虽然)。
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
相反,未设置()可以被动态地在foreach循环使用:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
通过复制阵列
删除数组键还存在尚未被提及另一实践。 有时候,最简单的方法来摆脱某些数组键是简单地复制$阵列1到$数组2。
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
显然,同样的方法适用于文本串:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
<强>输出强>
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
移除基于密钥的数组元素:
使用unset
功能象下面这样:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
基于值移除一个数组元素:
使用array_search
函数获得元素键,并使用上述方式,以除去一个数组元素象下面这样:
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
<?php
$array = array("your array");
$array = array_diff($array, ["element you want to delete"]);
?>
在变量$array
创建数组,然后在那里我已经把你放像“要删除元素”:“一”。如果你想删除多个项目,然后:“A”,“B”
使用以下代码:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
两种方式与保持索引的顺序,还可以,如果你不知道密钥的名称的第一个项目删除数组的第一个项目。
溶液#1
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
溶液#2
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
有关该样品数据:
$array = array(10 => "a", 20 => "b", 30 => "c");
您必须有这样的结果:
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}
使用array_search拿到钥匙,并删除它未设置如发现:
if (($key = array_search('word', $array)) !== false) {
unset($array[$key]);
}
对于具有非整数键的关联数组:
简单地, unset($array[$key])
会工作。
对于具有整数键的数组并且如果您想维护键:
$array = [ 'mango', 'red', 'orange', 'grapes'];
unset($array[2]); $array = array_values($array);
array_splice($array, 2, 1);
这可以帮助...
<?php
$a1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$a2 = array("a"=>"purple", "b"=>"orange");
array_splice($a1, 0, 2, $a2);
print_r($a1);
?>
其结果将是:
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
);
print_r($arrayName[1]);
// somevalue
unset($arrayName[1]);
print_r($arrayName);
unset
不改变索引,但array_splice
确实:
$arrayName = array('1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
array_splice($arrayName, 1, 2);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
unset($arrayName[1]);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )