有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
当前回答
如果您有一个数字索引数组,其中所有值都是唯一的(或者它们是非唯一的,但您希望删除特定值的所有实例),您可以简单地使用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
在本例中,值为“Charles”的元素被移除,这可以通过sizeof()调用进行验证,该调用报告初始数组的大小为4,移除后为3。
其他回答
unset($array[$index]);
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
有两种方法可以删除数组的第一项,同时保持索引的顺序,如果您不知道第一项的键名。
解决方案#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"
}
<?php
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
输出:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1
如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,那么array_filter()是最佳选择。那些从回调函数返回true的条目将被保留。
$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']]