注:mysqli_fetch_array()在PHP7過時,考慮使用的mysqli類FETCH_ASSOC()
我認爲你已經訂購了你的查詢,可能是通過mID,這將使這種方式更容易。 我的建議是,你創建一個數組,你收集你的數據,然後通過它循環創建表(我會順序寫出來,但你應該考慮把它分成類方法)。注意:這是未經測試的。
// execute the query
$result = mysqli_query($handler, $query);
// create a stack to collect the data
$data = array();
// the table header, will also be used to store values in order
$metaData = array(
'mID' => 'MemberID(system)',
'mFirst' => 'First Name',
// other meta data (make sure you use the field names)...
);
$grades = array(
'gReading' => 'Reading',
'gMath' => 'Math',
'gScience' => 'Science',
'gDaysAbsent' => 'Absent'
);
// create a table header
$tableHeader = $metaData;
// create 3 fields for each subject
foreach ($grades as $fieldname => $headline) {
$tableHeader[$fieldname . 'Q2'] = $headline . ' Q2';
$tableHeader[$fieldname . 'Q1'] = $headline . ' Q1';
$tableHeader[$fieldname . 'Performance'] = $headline . ' Performance';
}
// read each row of the result
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// we haven't handled this user before
if (!array_key_exists($row['mID'], $data)) {
// create a row with the meta data
$tableRow = array();
foreach ($metaData as $fieldname => $headline) {
$tableRow[$fieldname] = $row[$fieldname];
}
} else {
// fetch this users previous data
$tableRow = $data[$row['mID']];
}
// populate the grades for this quarter and calculate the performance
foreach ($grades as $gradename => $headline) {
// f.ex. gReadingQ1
$tableRow[$gradename . $row['gSemester']] = $row[$gradename];
// calculate the performance
if ($tableRow[$gradename . 'Q1'] && $tableRow[$gradename . 'Q2']) {
// TODO: do some magic here
// f.ex. calculate the number of the letter in the alphabet and get the average
$tableRow[$gradename . 'Performance'] = 'SOMETHING';
}
}
// store the row
$data[$row['mID']] = $tableRow;
}
// TODO: create the table in whatever format you want
print_r($data);
涵蓋了大部分,但我有兩個包含數據的查詢兩個數組。對每個數組執行此操作,然後將它們處理到第三個數組中? – user3107710
爲什麼你有兩個疑問?結果看起來像是來自同一張桌子。如果是這種情況,你應該使你的查詢更通用(f.ex.'學期IN(「Q1」,「Q2」)',以避免太頻繁地觸擊數據庫。 如果你確實需要做兩個查詢,結果是一個數組,而不是while循環來獲取行對你的結果棧做foreach。 – masterfloda