phpmoodlemoodle-api

how to get users per category and sub categories in moodle


I want to get the users per category. I'm using moodle 3.8 version. is there any method for get the users by category.


Solution

  • If you're looking for Moodle functions to do this, then you could probably call:

    $cat = core_course_category::get($categoryid);
    $courseids = $cat->get_courses(['recursive', 'idonly']);
    $userids = [];
    foreach ($courseids as $courseid) {
        $context = context_course::instance($courseid);
        $courseusers = get_enrolled_users($context, '', 0, 'u.id');
        $userids = array_merge($userids, array_keys($courseusers));
    }
    

    This is, however, horribly inefficient - you'd be best off writing a custom SQL query that, given the list of course ids, will generate a list of enrolled users for all of those courses (take a look inside the code of get_enrolled_users() to see how to build such an SQL query).