views:

39

answers:

3

I've around 80 instances of this class called Items and would like to efficiently search the objects by their ID or NAME.

<?php
class Item
{
    public $id;
    public $name;

   //methods
}
?>

I'm using PHP5.

+2  A: 

Assuming no duplicate names or IDs:

$ids = array();
$names = array();
foreach ($items as $item) {
  $ids[$item->id] = $item;
  $names[$item->name] = $item;
}

If you have duplicates (of names; I imagine there are no duplicate IDs by definition) then you need to work out how to handle that. You could store all the duplicates under one key (so the value becomes an array of matches).

Or do you mean a more sophisticated search? If so, a simple variant might be to break up the item name into words and/or phrases and then index them accordingly into an array.

cletus
is $items an array that contains references to objects? I wanted a simple search and the code you provided would do the job. Thanks
Arpit Tambi
+1  A: 

I would think about making an ItemIndex class;

this would allow you to maintain an arbitrary number of independent indexes, overloading the comparison and search functions as appropriate.

Hugh Bothwell
+1  A: 

If you have 80 instances, it really doesn't matter which option you use. Even if your search is N squared, I don't think it's worth it to invest time into a performance optimization here. Do the simplest thing and then profile; if it's horrible, only then consider increasing the complexity of the implementation to make it faster.

Alex