请帮助将下面的foreach代码限制为仅输出4个结果,并按desc顺序输出。非常感谢!
foreach( $users_who_like as $id ) :
if ( $id != $user_id )
$output .= ' · <a href="' . bp_core_get_user_domain( $id ) . '" title="' . bp_core_get_user_displayname( $id ) . '">' . bp_core_get_user_displayname( $id ) . '</a>';
endforeach;
您可以使用count
并检查它是否为4
像这个
$count = 4;
foreach( $users_who_like as $id ){
if ( $id != $user_id )
$output .= ' · <a href="' . bp_core_get_user_domain( $id ) . '" title="'.bp_core_get_user_displayname( $id ) . '">' . bp_core_get_user_displayname( $id ) .'</a>';
if(count <=0)
break; //will break if statement and foreach
$count--; // reduce it by one
}
#delete $user_id from array $users_who_like , we would not compare it any times
$users_list = array_diff($users_who_like,array($user_id));
#sort the array
rsort($users_list);
#set the limit we want to show
$limit = 4;
#use for better than foreach
for($i=0;$i<$limit;$i++){
$id = $users_list[$i];
#do sometings
}
在从数据库中选择数据时需要进行此操作
使用ODER BY ... DESC
排序,LIMIT
限制,WHERE
过滤掉当前用户。