我同意上面的答案,但为了完整起见(当您没有唯一ID可用作键时),我删除数组中值的首选方法如下:
function array_remove(&$array, $value)
{
return array_filter($array, function($a) use($value) {
return $a !== $value;
});
}
function array_remove_object(&$array, $value, $prop)
{
return array_filter($array, function($a) use($value, $prop) {
return $a->$prop !== $value;
});
}
以下是使用方式:
$values = array(
1, 2, 5, 3, 5, 6, 7, 1, 2, 4, 5, 6, 6, 8, 8,
);
print_r(array_remove($values, 6));
class Obj {
public $id;
public function __construct($id) {
$this->id = $id;
}
}
$objects = array(
new Obj(1), new Obj(2), new Obj(4), new Obj(3), new Obj(6), new Obj(4), new Obj(3), new Obj(1), new Obj(5),
);
print_r(array_remove_object($objects, 1, 'id'));
SplObjectStorage
实现了ArrayAccess
。 - Ionuț G. Stansearch_array()
返回false
,最好的做法是throw new OutOfBoundsException("No matching Observer found attached to the subject.")
。仔细考虑,附加的Observer
不再存在将是一个异常情况! :-) - Anthony Rutledge