Search code examples
phpmysqldatabasebuddypress

Limit number of results returned from database


I have the following code from a PHP website that, when called, returns a list of administrators in the database for user groups on the website:

function bp_group_list_admins( $group = false ) {
global $groups_template;

if ( empty( $group ) )
    $group =& $groups_template->group;

if ( !empty( $group->admins ) ) { ?>
    <ul id="group-admins">
        <?php foreach( (array) $group->admins as $admin ) { ?>
            <li>
                <a href="<?php echo bp_core_get_user_domain( $admin->user_id, $admin->user_nicename, $admin->user_login ) ?>"><?php echo bp_core_fetch_avatar( array( 'item_id' => $admin->user_id, 'email' => $admin->user_email, 'alt' => sprintf( __( 'Profile picture of %s', 'buddypress' ), bp_core_get_user_displayname( $admin->user_id ) ) ) ) ?></a>
            </li>
        <?php } ?>
    </ul>
<?php } else { ?>
    <span class="activity">No Admins</span>
<?php } ?>

I'd like to limit the number of results returned to a maximum of two (i.e. two administrators listed). Can this be achieved by altering the code above? How would I go about this?


Solution

  • The best would be to limit the data directly in the query, answered by another user.

    If, and only if, you for some reason can not change the query/data, then just break out of the loop

    function bp_group_list_admins( $group = false ) {
    global $groups_template;
    
    if ( empty( $group ) )
        $group =& $groups_template->group;
    
    if ( !empty( $group->admins ) ) { ?>
        <ul id="group-admins">
            <?php
            $i = 0;
            foreach( (array) $group->admins as $admin ) { ?>
                <li>
                    <a href="<?php echo bp_core_get_user_domain( $admin->user_id, $admin->user_nicename, $admin->user_login ) ?>"><?php echo bp_core_fetch_avatar( array( 'item_id' => $admin->user_id, 'email' => $admin->user_email, 'alt' => sprintf( __( 'Profile picture of %s', 'buddypress' ), bp_core_get_user_displayname( $admin->user_id ) ) ) ) ?></a>
                </li>
            <?php
            $i++;
            if ($i >= 2) { break; }
            } ?>
        </ul>
    <?php } else { ?>
        <span class="activity">No Admins</span>
    <?php } ?>