簡體   English   中英

解析mySQL查詢結果並為if / else形成數組

[英]Parse mySQL query results and form array for if/else

我需要獲取表中一列中的所有值,以便為另一個查詢創建白名單。 這是我得到的方式:

$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是,我需要為$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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM