php - 从 php 数组中获取键并使用 SQL WERE .. IN .. 子句过滤结果
问题描述
我有以下动态 $array1:
array(6) { [1]=> string(5) "false"
[2]=> string(5) "true"
[3]=> string(5) "false"
[4]=> string(5) "false"
[5]=> string(5) "true"
[10]=> string(5) "false"
}
- 我想做什么来使用循环创建带有 $array1 键的 $array2 ,其中值 =“true”。所以最后我有:
$array2 = (2, 5);
- 然后使用这个数组(使用 bind_param)用“WHERE ... IN ...”过滤我的结果:
if ($result = $link->prepare("SELECT sapp.appointment_id, sapp.time_start
FROM ss_appointments sapp
WHERE sapp.service_id IN ? AND sapp.time_start >= ?
")) {
$result->bind_param('ss', $array2, $period_from);
$result->execute();
$result->bind_result($app_id, $time_start);
while($result->fetch()){
echo '..results here..';
}
我正在为第一个而苦苦挣扎,所以甚至无法检查第二个 - 如果我可以将 $array2 完全绑定到字符串。
希望很清楚。
解决方案
你的问题的两个部分
要过滤您可以使用的数组array_filter()
,就像您使用字符串一样,您需要检查该值是否为“true”以过滤掉“false”值...
$array2 = array_keys(array_filter($array1, function($data) { return $data == "true"; }));
用于array_keys()
获取索引列表..
下一部分是构建 SQL,然后绑定值。您应该?
为每个值构建一个带有适当数量的占位符的查询
SELECT sapp.appointment_id, sapp.time_start
FROM ss_appointments sapp
WHERE sapp.service_id IN (?,?) AND sapp.time_start >= ?
那么 bind 也将是(例如)......
$result->bind_param('iis', 2, 5, $period_from);
因此,它iis
动态构建数据类型和要绑定的字段列表。然后使用参数 unpacking ( ...
) 运算符将它们放入...
// Build comma separater list of placeholders
$in = trim(str_repeat("?,", count($array2)),",");
// Create appropriate bind data type string
$type= str_repeat("i", count($array2));
$sql = "SELECT sapp.appointment_id, sapp.time_start
FROM ss_appointments sapp
WHERE sapp.service_id IN (".$in.") AND sapp.time_start >= ?";
if ($result = $link->prepare($sql)) {
// Add the period to the bind data
$array2[] = $period_from;
$result->bind_param($type.'s', ...$array2);
$result->execute();
$result->bind_result($app_id, $time_start);
while($result->fetch()){
echo '..results here..';
}
}
推荐阅读
- c++ - 内置类型 default-value-initialization 的区别
- c# - 为什么 Autofac 的动态实例化 (Func ) 的隐式关系类型尊重生命周期范围?
- ios - SwiftUI:ForEach 无法推断复杂的闭包返回类型
- sas - SAS 并行运行两个数据步骤
- python - 如何重定向到我使用 urllib.request 下载的文件,以便用户在我的烧瓶应用程序上查看?
- kubernetes - 有没有办法在不使用入口/网关的情况下在 kubernetes 服务级别上设置金丝雀或加权部署?
- javascript - Flow js谓词函数
- css - 如何更改导航栏下拉区域中文本的颜色?
- python - 如何使用 Python 和 Selenium 确认“find_element_by”搜索的结果?
- pdf - 是否可以从代码而不是 HTML 到 PDF 转换创建 PDF