Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way to search object in an array by a property

Tags:

well, having something like:

$array[0]->id = 'one'; $array[0]->color = 'white'; $array[1]->id = 'two'; $array[1]->color = 'red'; $array[2]->id = 'three'; $array[2]->color = 'blue'; 

what would be the fastest, most efficient way to implement a method like

function findObjectById($id){}

that would return the object $array[0] if i called:

$obj = findObjectById('one') 

and would return false if i passed 'four' as a param.

like image 490
André Alçada Padez Avatar asked Aug 18 '11 11:08

André Alçada Padez


People also ask

How do you filter one property from an array of objects?

Using filter() on an Array of Numbersvar newArray = array. filter(function(item) { return condition; }); The item argument is a reference to the current element in the array as filter() checks it against the condition . This is useful for accessing properties, in the case of objects.


1 Answers

You can iterate that objects:

function findObjectById($id){     $array = array( /* your array of objects */ );      foreach ( $array as $element ) {         if ( $id == $element->id ) {             return $element;         }     }      return false; } 

Edit:

Faster way is to have an array with keys equals to objects' ids (if unique);

Then you can build your function as follow:

function findObjectById($id){     $array = array( /* your array of objects with ids as keys */ );      if ( isset( $array[$id] ) ) {         return $array[$id];     }      return false; } 
like image 83
hsz Avatar answered Nov 06 '22 00:11

hsz