private function group_posts_by_discussion(array $forums, array $discussions, array $posts) : array {
        return array_reduce($posts, function($carry, $post) use ($forums, $discussions) {
            $discussionid = $post->get_discussion_id();
            if (!isset($discussions[$discussionid])) {
                throw new moodle_exception('Unable to find discussion with id ' . $discussionid);
            }

            if (isset($carry[$discussionid])) {
                $carry[$discussionid]['posts'][] = $post;
            } else {
                $discussion = $discussions[$discussionid];
                $forumid = $discussion->get_forum_id();

                if (!isset($forums[$forumid])) {
                    throw new moodle_exception('Unable to find forum with id ' . $forumid);
                }

                $carry[$discussionid] = [
                    'forum' => $forums[$forumid],
                    'discussion' => $discussions[$discussionid],
                    'posts' => [$post]
                ];
            }

            return $carry;
        }, []);
    }