微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何针对数组运行foreach并将其包含在SQL查询中?

所以我希望能够从数组中获取值并在SQL查询中使用它,并从这些行中获取信息.我目前的代码是这样的:

$config['exclude_devices'] = array('1','5');
$exclude = $config['exclude_devices'];
foreach ($exclude as $excluded) {
    $deviceinformation = MysqLi_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
}
while ($row = MysqLi_fetch_assoc($deviceinformation)) {
    // do stuff here
    // write to a variable for use in a table
}

但是,这给出了设备1,2,3,4的输出.

如果我移动foreach以包括while,它会产生2,3,4,5,1,2,3,4:

$exclude = $config['exclude_devices'];
foreach ($exclude as $excluded) {
    $deviceinformation = MysqLi_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
    while ($row = MysqLi_fetch_assoc($deviceinformation)) {
        // do stuff here
    }
}

如何修改代码以仅生成配置中未列出的设备?

解决方法:

在示例1中:

你跑:

SELECT * FROM `devices` WHERE `device_id` NOT IN(3)

然后

SELECT * FROM `devices` WHERE `device_id` NOT IN(5)

然后,您只获取第二个查询结果,因此您应该返回非5的设备作为其ID.

我会使用内爆,所以你排除了你不想要的所有id.

$excluded = implode(',', $config['exclude_devices']);
$deviceinformation = MysqLi_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
while ($row = MysqLi_fetch_assoc($deviceinformation)) {
    // do stuff here
}

演示:https://eval.in/536862
sql演示:http://sqlfiddle.com/#!9/e4ed47/2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐