Question

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?

Était-ce utile?

La 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 } ?>

Autres conseils

Your code isn't very helpful because it's not clear whether the array of administrators was retrieved from a MySQL query, and if so where.

However, the easy way to do what you want is to change your for-each loop to a for-loop that has only two iterations. In that case you'd be displaying only the first two administrators in the array.

If the group of administrators was retrieved from a MySQL query, you'd have to find that query and add the clause limit 2 to the end of it.

Use LIMIT 2 for example.

SELECT * FROM `table` WHERE `condition` = ? LIMIT 10
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top