Working with WordPress and using its functions to query the database on two custom tables. I am trying to output data as a “tree/grouped” format. Example:
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...
I am not sure of what would be needed to get the results to display this way. Here is one query I have that joins the tables…
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 );
I can certainly get results doing the following…
foreach ( $teamlist as $teamrow )
{
echo 'Team: ' . $teamrow->teamname . '<br />';
echo 'Player ID: ' . $teamrow->fname . '<br />';
}
But the team name will be duplicated in the results as
Team Name One
- Player One
Team Name One
- Player Two
Team Name One
- Player Three
- Etc...
I am fairly certain I need to add a nested loop in there, but I am uncertain as to the coding required.
Any thoughts or direction would be very much helpful to a guy who just lost a good portion of his hair on this. ; )
Not sure on the etiquette for answering your own question but I was able to get what I needed based on nesting the second query within a loop.
It needs cleaning up but does work for me.
You need a
Group by
on the teamid.Examples: http://www.techonthenet.com/sql/group_by.php
Edit you need to write two loops.