Find array key in objects array given an attribute value
I have an objects array like this:
Array
(
[945] => member Object
(
[id] => 13317
[name] => Test 999
[last_name] => Test 999
)
[54] => member Object
(
[id] => 13316
[name] => Manuel
[last_n开发者_如何学运维ame] => Maria parra
)
[654] => member Object
(
[id] => 13315
[name] => Byron
[last_name] => Castillo
)
[656] => member Object
(
[id] => 13314
[name] => Cesar
[last_name] => Vasquez
)
)
I need to remove one of these objects according to an attribute value.
For example, I want to remove from the array the object id 13316.Here is the functional approach:
$neededObjects = array_filter(
$objects,
function ($e) use ($idToFilter) {
return $e->id != $idToFilter;
}
);
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);
Use array search function :
//return array index of searched item
$key = array_search($search_value, array_column($list, 'column_name'));
$list[key]; //return array item
Since there is already plenty solutions given, I suggest an alternative to using the array:
$storage = new SplObjectStorage; // create an Object Collection
$storage->attach($memberObject); // add an object to it
$storage->detach($memberObject); // remove that object
You could make this into a custom MemberCollection
class with Finder methods and other utility operations, e.g.
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);
}
}
}
}
Might be overkill for your scenario though.
foreach ($array as $key=>$value)
if ($value->id==13316) {
unset($array[$key]);
break;
}
精彩评论