Find array key in objects array given an attribute value

大憨熊 提交于 2019-11-26 20:33:53

问题


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_name] => 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.


回答1:


Here is the functional approach:

$neededObjects = array_filter(
    $objects,
    function ($e) {
        return $e->id != 13316;
    }
);



回答2:


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);



回答3:


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.




回答4:


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



回答5:


   foreach ($array as $key=>$value)
      if ($value->id==13316) {
         unset($array[$key]);
         break;
      }


来源:https://stackoverflow.com/questions/4166198/find-array-key-in-objects-array-given-an-attribute-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!