有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?

我以为将其设置为null就可以了,但显然它不起作用。


当前回答

<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

输出:

[
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
]

fruit1

其他回答

使用以下代码:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
unset($array[$index]);

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"
    }
}

请注意,如果对象多次出现,则只会在第一次出现时删除它!

// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}

我只想说,我有一个具有可变属性的特定对象(它基本上映射了一个表,我正在更改表中的列,因此反映表的对象中的属性也会发生变化):

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的全部目的只是,所以当代码发生更改时,我不必查看代码中的任何地方,我只需查看类的开头并更改属性列表和$fields数组内容以反映新属性。