我有一个像这样的对象数组:
Array
(
[945] => member Object
(
[id] => 13317
[name] => Test 999
[last_name] => Test 999
)
[54] => member Object
(
[id] => 13316
[name] => Manuel
[last_name] => Maria parra
)
[654] => member Object
(
[id] => 13315
[name] => Byron
[last_name] => Castillo
)
[656] => member Object
(
[id] => 13314
[name] => Cesar
[last_name] => Vasquez
)
)
我需要根据属性值删除其中一个对象 例如,我想从数组中删除对象id 13316。
答案 0 :(得分:74)
这是功能性方法:
$neededObjects = array_filter(
$objects,
function ($e) {
return $e->id != 13316;
}
);
答案 1 :(得分:4)
function filter_by_key($array, $member, $value) {
$filtered = array();
foreach($array as $k => $v) {
if($v->$member != $value)
$filtered[$k] = $v;
}
return $filtered;
}
$array = ...
$array = filter_by_key($array, 'id', 13316);
答案 2 :(得分:3)
由于已经提供了大量的解决方案,我建议使用该阵列的替代方案:
$storage = new SplObjectStorage; // create an Object Collection
$storage->attach($memberObject); // add an object to it
$storage->detach($memberObject); // remove that object
您可以使用Finder方法和其他实用程序操作将其转换为自定义MemberCollection
类,例如
class MemberCollection implements IteratorAggregate
{
protected $_storage;
public function __construct()
{
$this->_storage = new SplObjectStorage;
}
public function getIterator()
{
return $this->_storage;
}
public function addMember(IMember $member)
{
$this->_storage->attach($member);
}
public function removeMember(IMember $member)
{
$this->_storage->detach($member);
}
public function removeBy($property, $value)
{
foreach ($this->_storage as $member) {
if($member->$property === $value) {
$this->_storage->detach($member);
}
}
}
}
虽然你的场景可能有点过头了。
答案 3 :(得分:2)
使用数组搜索功能:
//return array index of searched item
$key = array_search($search_value, array_column($list, 'column_name'));
$list[key]; //return array item
答案 4 :(得分:0)
foreach ($array as $key=>$value)
if ($value->id==13316) {
unset($array[$key]);
break;
}