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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With