SQL works in two dimensional data sets; you can't get the "game > party > user list" tree you want directly. You can do this by getting all the results from your table, then building the tree in PHP:
Code: Select all
$db = new PDO(
'mysql:dbname=test',
'root',
'root',
[
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]
);
$res = $db->query('SELECT game_id, party_id, user_id, point FROM results ORDER BY game_id, party_id');
$results = [];
foreach ($res as $row) {
if (!isset($results[$row->game_id])) {
$results[$row->game_id] = [
'game' => $row->game_id,
'parties' => []
];
}
if (!isset($results[$row->game_id]['parties'][$row->party_id])) {
$results[$row->game_id]['parties'][$row->party_id] = [
'party' => $row->party_id,
'users' => []
];
}
$results[$row->game_id]['parties'][$row->party_id]['users'][$row->user_id] = [
'user' => $row->user_id,
'point' => $row->point
];
}
Once you have your data structure, you can loop through it to print out your results:
Code: Select all
foreach ($results as $game) {
echo 'Game: ' . $game['game'], PHP_EOL;
foreach ($game['parties'] as $party) {
echo 'Party: ' . $party['party'], PHP_EOL;
foreach ($party['users'] as $user) {
echo 'User ' . $user['user'] . ': ' . $user['point'], PHP_EOL;
}
echo PHP_EOL;
}
}
This looks complicated, but most of the gnarliness is in the setting up of the tree structure.