Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find array key in objects array given an attribute value

Tags:

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.

like image 260
el_quick Avatar asked Nov 12 '10 15:11

el_quick


People also ask

How do you get the key of an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you check if a key exists in an array of objects JavaScript?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.

How do you check if an array of objects contains a value in react?

To check if an element exists in an array in React: Use the includes() method to check if a primitive exists in an array. Use the some() method to check if an object exists in an array.


2 Answers

Here is the functional approach:

$neededObjects = array_filter(     $objects,     function ($e) use ($idToFilter) {         return $e->id != $idToFilter;     } ); 
like image 192
erisco Avatar answered Sep 29 '22 08:09

erisco


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); 
like image 32
Jacob Relkin Avatar answered Sep 29 '22 08:09

Jacob Relkin