簡體   English   中英

PHP + MYSQL-遍歷基於表的數據

[英]PHP + MYSQL - Looping Through Table Data Based

我目前有一個MySQL數據庫,該數據庫包含一個表,該表包含一組特定單詞的數據。 結構是這樣的(當然還有更多的數據):

**ID**        **word**        **number**
----------------------------------------
  1             Test              10
  2             Test              14
  3             Test              20
  4             Apple             7
  5             Apple             8
  6             Apple             11
  7             Bus               3
  8             Bus               3
  9             Bus               5

其中ID是唯一鍵。

我想做的是從此表中獲取所有數據,並遍歷該表以獲取每個“單詞”集的“ Number”數據,以便運行一些總和。

因此,我想獲取所有數據,然后遍歷數據並為每個單詞集做一些if語句,例如:獲取與單詞Test相關的所有數字,然后與Apple等相關的所有數字,等等。因為這個詞不是唯一鍵,所以我不確定從數據庫中提取數據后如何拆分數據。

到目前為止,我有以下幾點:

public function getData() {

        $query = $this->db->prepare("SELECT * FROM table");
        $query->execute();

    try{

        $query->execute();
        $result = $query->fetchAll();

    }catch(PDOException $e){
        die($e->getMessage());
    }

}

所以很明顯,我已經根據需要從數據庫中提取了所有數據,並且可以print_r返回的數據數組而沒有任何問題。 現在,我想遍歷數據並為每個單詞集完成一個特定的功能。 例如:運行一條if語句,檢查單詞“ Test”的3個數字是否相同,然后運行相同的檢查以查看“ Apple”的3個數字是否相同,然后再次顯示“ Bus”等。

例如,在循環/檢查的最后,我希望能夠回顯一條語句:“單詞Bus包含2個匹配數字”

在SQL查詢中的操作方法如下:

SELECT word, COUNT(DISTINCT number) = 1 AS numbers_all_the_same
FROM table
GROUP BY word

使用您的數據將返回:

word    numbers_all_the_same
Test    0
Apple   0
Bus     0

因為他們的分組中沒有一個都相同。 如果任何一個單詞都具有相同的數字,則第二列中將帶有1

您可以按照以下方式創建所有數據的數組,並按單詞分組:

$all_words = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $word = $row['word'];
    $number = $row['number'];
    if (!isset($all_words[$word])) { // We haven't seen this word before
        $all_words[$word] = array($number); // Create an array with the number
    } else {                         // We have seen this word before
        $all_words[$word][] = $number; // Add the number to the array
    }
}

現在,您可以對與每個單詞相關的數字執行任何類型的分析。 如果您想知道所有數字是否都相同,可以執行以下操作:

$uniq = array_unique($all_words["Apple"]);
if (count($uniq) == 1) ...

暫無
暫無

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

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