如果您查詢的是RaceName
,則應該這樣做。
<?php
$query = "SELECT CandidateName, CandidateVotes, Party, MainRaceName, RaceName, win
FROM candidates
WHERE RaceID = $RaceID";
$result = mysql_query($query) or die(mysql_error());
for ($i = 0; $row = mysql_fetch_array($result), $i++) {
// Print out main race name and race name on first iteration only
if ($i === 0) {
?>
<h1><?php echo $row['MainRaceName'] ?></h1>
<h1><?php echo $row['RaceName'] ?></h1>
<?php
}
?>
<p><?php echo $row['CandidateName'] ?></p>
<p><?php echo $row['CandidateVotes'] ?></p>
<?php
}
?>
如果你要查詢MainRaceName
,你需要在主競賽打印出所有的比賽,我會組比賽名稱與候選人一起,並獲得特定種族的名字像這樣總的候選人表決。
<?php
$query = "SELECT CandidateName, CandidateVotes, Party, MainRaceName, RaceName, win
FROM candidates
WHERE RaceID = $RaceID";
$result = mysql_query($query) or die(mysql_error());
$grouped_result = array();
$total_votes = 0;
$main_race = '';
for ($i = 0; $row = mysql_fetch_array($result), $i++) {
// If it is first iteration, set the current race name to race name in row
// and save main race name
if ($i === 0) {
$main_race = $row['MainRaceName'];
$cur_race = $row['RaceName'];
}
// If current race name is different than race name in row we reset
// total count of votes, since we need to have sum of votes grouped by race name
if ($cur_race != $row['RaceName']) {
$total_votes = 0;
}
// Populate grouped array
$grouped_result[$row['RaceName']]['candidates'][] = array(
'name' => $row['CandidateName'],
'votes' => $row['CandidateVote']
);
$grouped_result[$row['RaceName']]['total_votes'] = $total_votes + $row['CandidateVotes'];;
}
從你的照片$grouped_result
會給你一個這樣的嵌套數組。
array(
'President' => array(
'candidates' => array(
0 => array(
'name' => 'Mr. X',
'votes' => 429
),
1 => array(
'name' => 'Ms. Y',
'votes' => 43
),
.
.
.
),
'total_votes' => 5247
),
'US House of ...' => array(
'candidates' => array(
0 => array(
'name' => 'whatever_his_name_is',
'votes' => 3693
)
)
'total_votes' => 3693
)
)
現在你可以去打印出html了。
<h1><?php echo $main_race ?></h1>
<?php
// loop through all races
foreach ($grouped_result as $racename => $data):
?>
<h1><?php echo $racename ?></h1>
<?php
// loop through all candidates in this race
foreach ($data['candidates'] as $candidate):
?>
<p><?php echo $candidate['name'] ?></p>
<p><?php echo $candidate['votes'] ?></p>
<!-- Calculate vote percentages -->
<p><?php echo ($candidate['votes']/$data['total_votes']) * 100 ?> %</p>
<?php
endforeach;
?>
<h1>Total votes: <?php echo $data['total_votes'] ?></h1>
<?php
endforeach;
?>
現在你可以樣式一切,投入到表中,無論...
有在你的代碼沒有嵌套循環。它應該做什麼,它做的是什麼? – Barmar
如果您不打算使用它,爲什麼要對代碼進行故障診斷?所有'mysql_ *'函數已被棄用多年,可用替代品超過十年。轉到PDO。 – miken32
Barmar我知道。那是我需要幫助的地方。我添加了另一張圖片來顯示我需要幫助的位置。可能有其他解決方案而不是嵌套語句。謝謝 – CyberFla