1

使用 Wordpress 并使用其功能在两个自定义表上查询数据库。我正在尝试将数据输出为“树/分组”格式。例子:

Team Name One
- Player Name One
- Player Name Two
- Player Name Three
- Etc...

Team Name Two
- Player Name one
- Player Name Two
- Player Name Three
- Etc...

我不确定要以这种方式显示结果需要什么。这是我有一个连接表的查询......

global $wpdb;
$user_id = '1';
$teamlist = $wpdb->get_results( $wpdb->prepare( 
"
SELECT
fv_teams.team_id AS team_teamid,
fv_players.player_id,
fv_teams.team_name AS teamname,
fv_players.player_fname AS fname,
fv_players.player_lname AS lname,
fv_players.player_team AS team,
fv_players.player_position AS position
FROM
fv_teams
INNER JOIN fv_players ON fv_teams.team_id = fv_players.team_id
WHERE
fv_teams.user_id = %d
",
$user_id
), OBJECT );

我当然可以通过以下方式获得结果...

foreach ( $teamlist as $teamrow ) 
{
echo 'Team: ' .  $teamrow->teamname . '<br />';
echo 'Player ID: ' .  $teamrow->fname . '<br />';
}

但是团队名称将在结果中重复为

Team Name One
- Player One
Team Name One
- Player Two
Team Name One
- Player Three
- Etc...

我相当确定我需要在其中添加一个嵌套循环,但我不确定所需的编码。

任何想法或方向都会对一个刚刚失去大部分头发的人非常有帮助。; )

4

2 回答 2

3

不确定回答您自己问题的礼仪,但我能够通过将第二个查询嵌套在循环中来获得所需的内容。

$teamlist = $wpdb->get_results( $wpdb->prepare( 
"SELECT *
 FROM fv_teams
 WHERE user_id = '1'
",
$user_id
), OBJECT );


foreach ( $teamlist as $teamrow ) 
{
$get_team_id = $teamrow->team_id;
echo  '<hr>';
echo '<h2>' . $teamrow->team_name . '</h2>';
$playerlist = $wpdb->get_results( $wpdb->prepare( 
    "SELECT *
     FROM fv_players 
     WHERE team_id = %d
    ",
    $get_team_id
), OBJECT );


    echo '<ul>';
    foreach ( $playerlist as $playerrow ) 
    {
        echo '<li>Player Name: ' .  $playerrow->player_fname . '</li>';
    }
    echo '</ul>';   
}

它需要清理,但对我有用。

于 2012-06-25T19:37:37.003 回答
0

你需要一个Group by在teamid上。

示例:http ://www.techonthenet.com/sql/group_by.php

编辑你需要写两个循环。

<?php 
 // in plain language
 if(TeamName has another value)
  display name;
   if (playername has another value)
    display playername;
   end if
 end if
 ?>
于 2012-06-25T19:06:10.860 回答