我从这个论坛中学到了很多东西,并提前感谢。基本上,我正在尝试为多个表的数据库查询的结果做“脚注”。我的表中有几种生物材料的“书目参考”,但我无法以更具可读性的方式整合结果。我想我需要使用多维数组,但我认为必须有一种更优雅的方式。 php代码中的MySQL部分是:
$queryFromAgentBW = "SELECT DISTINCT reports.ID, reports.link, agent_names.ID, agent_names.Name, agent.BW_Actor_List, agent.Common_Name, agent.Reference, actor_list.ID
FROM agent_names, agent
JOIN actor_list ON(agent.BW_Actor_List = actor_list.ID)
JOIN reports ON(agent.Reference = reports.ID)
WHERE agent_names.ID = agent.Agent_Name AND BW_Actor_List = '".mysql_real_escape_string($a)."'";
$resultFromAgentBW = mysql_query($queryFromAgentBW);
//check result; show error for debugging
if (!$resultFromAgentBW)
{
$message = 'Invalid query:'.mysql_error()."\n";
$message .= 'Whole query:'.$queryFromAgentBW;
die($message);
}
while ($rowBW = mysql_fetch_assoc($resultFromAgentBW))
{
// Need to get all this in an array and then print out later so agents
are listed only once with all of the corresponding reference numbers
$bwArray[] = $rowBW;
}
php的“漂亮打印”部分代码是:
foreach ($bwArray as $bw)
{
echo "Name: {$bw['Name']}<br />"
. "Ref: {$bw['Reference']}<br />"
. "Link: {$bw['link']}<br /><br />";
}
结果现在是:
Name: Abrin toxin
Ref: 1
Link: C:\wamp\www\References\Abrin\AbrinandRicin_Patocka.pdf
Name: Abrin toxin
Ref: 6
Link: C:\wamp\www\References\Abrin\TheEmergencyResponseSafetyandHealthDatabase_ Biotoxin_ ABRIN.pdf
Name: Adenovirus
Ref: 9
Link: C:\wamp\www\References\Adenovirus\Adenovirus (Serotypes 40 & 41)_PHAC .pdf
Name: Adenovirus
Ref: 13
Link: C:\wamp\www\References\Adenovirus\AdenovirusSerotype31InfectioninaNewbornGirlandReviewoftheLiterature.pdf
但最理想的是:
Abrin Toxin [1, 6]
Adenovirus [9, 13]
其中数字是现在显示为文本的href链接(PDF文档参考)。感谢您对本案中最好的帮助或指导!
答案 0 :(得分:1)
您只需要在数组中正确汇总结果。将最后两个循环更改为:
while ($rowBW = mysql_fetch_assoc($resultFromAgentBW)) {
$bwArray[$rowBW['Name']][] = $rowBW;
}
foreach ($bwArray as $name => $refs) {
echo 'Name: ' . $name . ' [';
for ($i = 0; $i < count($refs); $i++) {
echo ($i > 0 ? ' ' : '') . '<a href="' . $ref['link'] . '">' . $ref['Reference'] . '</a>';
}
echo ']<br />';
}
为了更好的可读性,我省略了使用htmlspecialchars()
转义的数据。
答案 1 :(得分:1)
您应该在查询中添加 group_concat 功能和 group by 子句,并在mysql中完成所有工作
SELECT group_concat(agent.Reference SEPARATOR ','), agent_names.ID, agent_names.Name
FROM agent_names, agent
JOIN actor_list ON(agent.BW_Actor_List = actor_list.ID)
JOIN reports ON(agent.Reference = reports.ID)
WHERE agent_names.ID = agent.Agent_Name AND BW_Actor_List = '".mysql_real_escape_string($a)."'
GROUP BY agent_names.ID