Codeigniter selecting data with multiple id's

2019-04-14 18:13发布

问题:

Here is an example of my code and an explanation what I am trying to do.

At the beginning of the code I am selecting three variables in my database. I then compare them to a function that determines the distance, if the distance is within the given distance then I have the id of that record. This will result in multiple id's. Could be five or none, depends on the variables given.

What I need to know is once I have determined that id I need to use I need to put into either a variable or something else that is manageable. Basically I need to take the list and query the database again to get the list of details from the database. The list will return objects that will later be past to json_encode for processing.

What I need to know is what is the best way to put each id into a variable and pass it to a database query and get the results I need.

I've tried using $dbStations->where('_id', '34,33,45') but it only returns the first value. I need something like WHERE _id = 34 AND 33 AND 45 if possible.

I am using Codeigniter for my framework and I have went over the documentation and I have not found a solution.

EDIT: Now that I have the the data selected from the database I need to get the distance to be displayed at the end of each record retrieved.

Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus"}]}

This is what it needs to be, keep in mind that distance is not in the database, it is calculated on the fly.

Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus", "distance": "1.2 Mi"}]}

Any ideas on how to get ths distance that is caculcated to be appended to the end of each result?

        $dbStations->select('lat');
        $dbStations->select('lng');
        $dbStations->select('_id');
        $stations = $dbStations->get('stDetails');
        foreach ($stations->result() as $station) {
            $lat2 = $station->lat;
            $lng2 = $station->lng;
            $stId = $station->_id;
            $distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M");
                if ($distance <= $rad) {
                //at this point the code has determined that this id is within
                //the preferred distance.
                $stationArr[] = $stId;
            }
        }
            $dbStations->select('country, _id, lat, lng, admin_level_1, locale');
            $dbStations->where_in('_id', $stationArr);
            $stations = $dbStations->get('stationDetails');
        echo json_encode(array('stations' => $stations->result()));
    }

回答1:

Try using where_in()

$ids = array(33, 34, 45);
$dbStations->where_in('id', $ids);
// Produces: WHERE id IN (33, 34, 45)

This will return records that have the ID of 33, 34, 45