mysql查询输出值ifelse,解析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);

If I var_dump $avails, I get this:

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

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 comes from AJAX

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' ))

If I var_dump $row, I get this:

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"

}

解决方案

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值