有人请帮助限制以下foreach代码仅输出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>';
endforeach;
答案 0 :(得分:1)
您可以使用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
}
答案 1 :(得分:1)
#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
}
答案 2 :(得分:0)
从数据库中选择数据时需要进行此操作
使用ODER BY ... DESC
订购,LIMIT
限制,WHERE
过滤掉当前用户。