有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
当前回答
遵循默认功能:
PHP:未设置
unset()销毁指定的变量。有关更多信息,请参阅PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
PHP:array_pop
函数的作用是删除数组的最后一个元素。有关更多信息,请参阅PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
PHP:array_splice
函数的作用是从数组中删除选定的元素,并用新的元素替换它。有关更多信息,请参阅PHP array_spling
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
PHP:array_shift
函数的作用是从数组中删除第一个元素。有关更多信息,请参阅PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
其他回答
如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,那么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']]
使用以下代码:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
如果指定了索引:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
如果我们有值而不是索引:
$arr = ['a', 'b', 'c'];
// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
if条件是必要的因为如果找不到索引,unset()将自动删除数组的第一个元素,这不是我们想要的。
Edit
如果无法将其视为对象位于该数组中,则需要添加检查:
if(in_array($object,$array)) unset($array[array_search($object,$array)]);
原始答案
如果要通过引用数组中的特定对象来删除该对象,可以执行以下操作:
unset($array[array_search($object,$array)]);
例子:
<?php
class Foo
{
public $id;
public $name;
}
$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';
$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';
$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';
$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);
echo '<pre>';
var_dump($array);
echo '</pre>';
?>
结果:
array(2) {
[0]=>
object(Foo)#1 (2) {
["id"]=>
int(1)
["name"]=>
string(5) "Name1"
}
[2]=>
object(Foo)#3 (2) {
["id"]=>
int(3)
["name"]=>
string(5) "Name3"
}
}
请注意,如果对象多次出现,则只会在第一次出现时删除它!
有两种方法可以删除数组的第一项,同时保持索引的顺序,如果您不知道第一项的键名。
解决方案#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"
}