tags:

views:

41

answers:

3

I have the mysql results ($date_options) as below

Array (
    [0] => stdClass Object (
        [id] => 4
        [start_date] => 2010-09-29
    )
    [1] => stdClass Object (
        [id] => 13
        [start_date] => 2010-10-06
    )
)

I need to be able to search in the "id" field if some value existed. I tried this and it didn't work:

array_search($event_id, $date_options, true)

$event_id is has the id value. I only want to look in id and not in start_date

How to solve this?

Thanks

+6  A: 

Since you're already using MySQL, why don't you select only the ID you are interested in? That would be more efficient than retrieving all records and then searching in PHP.


If you still want to do it this way, you can simply iterate over the array and check manually:

foreach ($date_options as $result) {
  if ($result->id == $event_id) {
     // do something
  }
}
casablanca
A: 

Try this:

function searchEventForId($eventId, $dateOptions){
    foreach($dateOptions as $event){
        if($event->id === $eventId){
            return $event;
        }
    }
    return null;
}

$event = searchEventForId($event_id, $date_options);
Colin Hebert
A: 

All answers are spot-on, but for the sake of expandability, here's a function that is "re-usable" and it's going to search recursively through even deeper arrays, with the possibility of specifying both the key and its value. It's going to stop at the first match and return its value, but again, for the sake of expandability it could quite easily be modified to return an array of matched key/value pairs, in case multiple results are expected.

function search_my_array($my_key, $my_value, $array) {
    foreach($array as $key => $value) {
        if(!is_array($value)) {
            if(($key == $my_key) && ($value == $my_value)) {
                return $value;
            }
         } else {
             if(($result = search_my_array($my_key, $my_value, $value)) !== false) {
                return $result;
             }
         }
    }
    return false;
}

So in your case, you'd be using it like:

$event = search_my_array('id', $event_id, $date_options);

I'd suggest however that you go for one of the much simpler solutions posted, if you only need the search function for this particular task, but maybe somebody will find this useful at some point.

FreekOne