内部连接数组结果与另一个表ID,名称

时间:2012-12-14 16:53:02

标签: php mysql arrays join foreach

是否可以获取数组的结果并将其与另一个表ID连接以输出ID的名称?

这是数组的输出:Array ( [0] => 3 [1] => 1 [2] => 2 )

这是mysql:

SELECT * 
FROM 
    meet 
    INNER JOIN location 
    ON meet.meetLoc = location.locID 
    LEFT JOIN team ON meet.meetTeams = team.teamID 
ORDER BY meetDate ASC

这是PHP,但是当我需要“Bob:Sally:Sue”时它只输出“3:1:2”:

$teams = explode(", ", $row_rsCurMeet['meetTeams']);
$tmp = array();
foreach ($teams as $team)
$tmp[] = $team;
echo implode('  :  ',$tmp);

我也尝试了这个,但它返回“Bob:Bob:Bob”

$team_id = $row_rsCurMeet['teamID'];    
$team_name = $row_rsCurMeet['teamName'];
$team = $row_rsCurMeet['teamName'];
$teams = explode(", ", $row_rsCurMeet['meetTeams']);
foreach ($teams as $key => $value) {
$key = $team_id;
$value = $team_name;
print_r ($value);
}

有什么想法?我的头因撞在墙上而受伤。谢谢!

SAMPLE DATA

Table meet             Table  team
meetID  meetTeams      teamID   teamName
1        3, 1, 2         1      Sally
2        2, 3, 1         2      Sue
3        1, 3, 2         3      Bob

请忽略位置信息,因为这不是问题。

1 个答案:

答案 0 :(得分:0)

您的第一个问题是,如果您希望能够真正将会议与团队联系起来,那么您需要进行架构更改。在1,2,3之类的meet.meetTeams中拥有值会阻止您在团队表上进行有意义的连接。

所以,我的建议是,您完全删除meet.meetTeams列,以支持具有此类结构的新表meetTeams(或任何您想要调用的表)

meetId    teamID
------    ------
  1         1
  1         2
  1         3
  2         1
  2         2
  2         3
etc. 

然后你会这样查询:

SELECT * 
FROM 
    meet 
    INNER JOIN location 
    ON meet.meetLoc = location.locID 
    INNER JOIN meetTeams
    ON meet.meetID = meetTeams.meetID
    INNER JOIN team
    ON meetTeams.teamID = team.teamID 
ORDER BY meet.meetDate ASC

如果您真正需要做的就是列出会议和团队,您可以从查询中删除位置表。您还可以通过不执行SELECT *来限制返回的字段,只返回您需要的字段。

现在您可能需要获取结果集并将其读入多维数组,并将meetID作为第一维。这很容易做到。它可能看起来像这样:

$meet_array = array()
while ($row = [YOUR PHP TO RETRIEVE ROW ARRAY FROM RESULT SET]) {
   $meet_array[$row['meetID']] = $row;
}

foreach ($meet_array as $meet_id => $meet_data) {
    echo 'Meet ID: ' . $meet_id . ' <br />';
    foreach ($meet_data as $data) {
        echo 'Team ID: ' . $data['teamID'] . ', Team Name: ' . $data['teamName'] . ' : ';
    }
    echo '<br />';
}