php - Codeigniter选择具有多个ID的数据

标签 php codeigniter

这是我的代码示例和我想要做的解释。

在代码的开头,我在我的数据库中选择了三个变量。然后我将它们与确定距离的函数进行比较,如果距离在给定的距离内,那么我就有了该记录的 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()));
    }

最佳答案

尝试使用 where_in()

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

这将返回 ID 为 33、34、45 的记录

关于php - Codeigniter选择具有多个ID的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605884/

相关文章:

javascript - 无法从 php codeigniter 中的 jquery、ajax 获取 Controller 中的值

php - 如何将 2 个字符串插入到数据库的 1 列中? (代码点火器)

javascript - 覆盖 SummerNote 图像弹出不起作用

php - SEOstats API SEMrush关键词查询方法?

php - 验证 PHP 和 Jquery 中的 url?

php - 将一个表与其他 4 个表连接起来 laravel eloquent

php - mysqli_fetch_assoc() 不返回任何东西

php - 限制 codeigniter 分页中的链接数量

php - 如何从 CodeIgniter 的 View 中替换制表符和新行?

javascript - 为什么当我使用 jquery.ajax 将 POST 发送到 PHP 脚本时整数会变成字符串