首页 > 解决方案 > 从 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" 
             }
  1. 我想做什么来使用循环创建带有 $array1 键的 $array2 ,其中值 =“true”。所以最后我有:
$array2 = (2, 5);
  1. 然后使用这个数组(使用 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 完全绑定到字符串。

希望很清楚。

标签: phpmysqlarrays

解决方案


你的问题的两个部分

要过滤您可以使用的数组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..';

    }
}

推荐阅读