2011-09-30 121 views
2

这是我的代码和解释我想要做的一个例子。Codeigniter选择多个ID的数据

在代码的开头,我在我的数据库中选择了三个变量。然后,我将它们与确定距离的函数进行比较,如果距离在给定距离内,那么我有该记录的ID。这将导致多个ID。可能是五个或没有,取决于给出的变量。

我需要知道的是,一旦我确定了我需要使用的id,我需要将其放入变量或其他可管理的内容中。基本上我需要重新列表并查询数据库以获取数据库中的详细信息列表。该列表将返回稍后将过去的对象,以便处理json_encode

我需要知道的是将每个id放入一个变量并将其传递给数据库查询并获得所需结果的最佳方法是什么。

我试过使用$dbStations->where('_id', '34,33,45')但它只返回第一个值。如果可能,我需要类似WHERE _id = 34 AND 33 AND 45

我在为我的框架使用Codeigniter,并且我已经阅读了文档,并且没有找到解决方案。

编辑:现在我有从数据库中选择的数据我需要得到的距离显示在每个记录检索结束。

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

这是它需要的,请记住,距离不在数据库中,它是在飞行中计算的。

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

任何关于如何获得距离的距离被追加到每个结果的末尾?

 $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())); 
    } 

回答

12

尝试使用where_in()

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

这将返回有33个,34号,45

+0

伟大的工作,我一直想把这个较早,但只是没有工作了记录。非常感谢。 –