解析mySQL查询结果并为if/else形成数组 [英] Parse mySQL query results and form array for if/else

查看:304
本文介绍了解析mySQL查询结果并为if/else形成数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取表中一列中的所有值,以便为另一个查询创建白名单.这是我得到的方式:

I need to get all the values in one column in a table so I can create a whitelist for another query. Here's how I'm getting that:

$stmt = $dbh->prepare("select GROUP_CONCAT( cohort_id SEPARATOR ',') as cohort_id from ( select distinct cohort_id from table_cohorts) as m"); 
$stmt->execute(); 
$row = $stmt->fetch();
$avails = json_encode($row);

如果我var_dump $avails,我会得到:

string(125) "{"cohort_id":"national_percent,database_percent,cohort_1,cohort_2","0":"national_percent,database_percent,cohort_1,cohort_2"}"

我想要的是带有"cohort_id"的东西.我需要形成一个数组,以便可以将其放入类似这样的地方:

The stuff with "cohort_id" is what I want. I need to form an array so I can drop it in something like this:

(in_array($sortvalue, $arrayofpossibleoptions))//$sortvalue来自AJAX

如何以正确的格式获取此信息?还有一点皱纹,我需要为$arrayofpossibleoptions或类似的东西添加一个附加值,但不确定正确的语法是什么:

How can I get this in the right format? One further wrinkle, I need to add one additional value to the $arrayofpossibleoptions or something like this, but not sure what the proper syntax is:

(in_array($sortvalue, $arrayofpossibleoptions || 'another' ))

如果我var_dump $row,我会得到:

array(2) {
  ["cohort_id"]=>
  string(51) "national_percent,database_percent,cohort_1,cohort_2"
  [0]=>
  string(51) "national_percent,database_percent,cohort_1,cohort_2"
}

推荐答案

如果您需要将此数据加载到in_array中,那么它应该采用数组形式,不能使用json字符串.

If you need this data to be loaded into in_array, then it should be in an array form, you can't use a json string.

$stmt = $dbh->prepare('SELECT DISTINCT cohort_id FROM table_cohorts'); 
$stmt->execute();
$cohort_ids = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $cohort_ids[] = $row['cohort_id'];
}

if(in_array($user_input, $cohort_ids)) {
    // do the rest
} else {
    // oops your input is not any of those
}

这篇关于解析mySQL查询结果并为if/else形成数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆