如果您查询的是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