有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
当前回答
有两种方法可以删除数组的第一项,同时保持索引的顺序,如果您不知道第一项的键名。
解决方案#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"
}
其他回答
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
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"
}
}
请注意,如果对象多次出现,则只会在第一次出现时删除它!
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
基于键删除数组元素:
使用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
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
输出:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1