我在php $ resultA和$ resultB中有两个来自SQL select语句的数组。该数组使用mysqli_fetch_array(MYSQLI_ASSOC)构建。我想比较每个科目的成绩,并获得改进,减少或保持相同的结果。在数组中比较这些值并将结果添加到新字段中的数组末尾(即ReadingPerformance,MathPerformance,SciencePerformance和&amp; AttendancePerformance)的最佳实践是什么,以便可以访问它们以显示在表中< / p>
Array ( [mID] => 1 [mFirst] => Mike [mLast] => Davis [mNumber] => 123456789 [mSchool] => SSAS [mGrade] => 8 [gID] => 0 [gYear] => 2017 [gReading] => A [gMath] => A [gScience] => B [gSemester] => Q1 [gDaysAbsent] => 1 )
Array ( [mID] => 1 [mFirst] => Mike [mLast] => Davis [mNumber] => 123456789 [mSchool] => SSAS [mGrade] => 8 [gID] => 1 [gYear] => 2017 [gReading] => B [gMath] => B [gScience] => A [gSemester] => Q2 [gDaysAbsent] => 4 )
最终表标题
答案 0 :(得分:0)
注意:在PHP7中不推荐使用mysqli_fetch_array(),考虑将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);