注: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