解析 mySQL 查询结果并为 if/else 形成数组
Parse mySQL query results and form array for if/else
我需要获取 table 中一列中的所有值,以便为另一个查询创建白名单。我是这样得到的:
$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"的东西就是我想要的。我需要形成一个数组,这样我就可以把它放在这样的地方:
(in_array($sortvalue, $arrayofpossibleoptions))
//$sortvalue
来自 AJAX
如何以正确的格式获取此文件?还有一个问题,我需要向 $arrayofpossibleoptions
或类似的东西添加一个附加值,但不确定正确的语法是什么:
(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字符串。
$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
}
我需要获取 table 中一列中的所有值,以便为另一个查询创建白名单。我是这样得到的:
$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"的东西就是我想要的。我需要形成一个数组,这样我就可以把它放在这样的地方:
(in_array($sortvalue, $arrayofpossibleoptions))
//$sortvalue
来自 AJAX
如何以正确的格式获取此文件?还有一个问题,我需要向 $arrayofpossibleoptions
或类似的东西添加一个附加值,但不确定正确的语法是什么:
(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字符串。
$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
}