开发者

Search in array query result in php/mysql

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开发者_C百科] => 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


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
  }
}


Try this:

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

$event = searchEventForId($event_id, $date_options);


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.


This is Tested you may try it, I have used in my one of projects

function FindData($fKey, $find_val, $res) {
        $arr = $res;//json_decode($res, true);
        foreach ($arr as $key => $value) {
            if ($value[$fKey] == $find_val) {
                return $value;
            }
        }
    }

example:

$row = FindData('KeyName', 'Value', 'ArrayData or mySql Result Set');

It wont hit MySQL Database each time to fetch patricular data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜