2013-02-17 94 views
1

有人請幫助限制下面的foreach代碼,以輸出4個結果,並按desc順序。非常感謝你!限制foreach輸出4結果

foreach($users_who_like as $id) : 

if ($id != $user_id) 
$output .= ' &middot <a href="' . bp_core_get_user_domain($id) . '" title="' . bp_core_get_user_displayname($id) . '">' . bp_core_get_user_displayname($id) . '</a>'; 

endforeach; 
+0

我們不寫的代碼你。請告訴我們你已經嘗試了什麼。 – Achrome 2013-02-17 05:21:21

+0

在這一點上,你最好使用常規的for-loop。 – 2013-02-17 05:22:51

+0

您必須提供帶出這些結果的mysql代碼 – 2013-02-17 05:26:47

回答

1

您可以使用count,並檢查它是否是4 這樣

$count = 4; 

foreach($users_who_like as $id){ 

if ($id != $user_id) 
$output .= ' &middot <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 

} 
+0

嗨,我在此行計數中遇到意外的T_DEC錯誤 - ;這段代碼的工作沒有計數 - ;但如果它超過4,則不會顯示任何結果。 – lukekiko 2013-02-17 05:44:33

+1

在'count - '上缺少'$'。 – 2013-02-17 05:45:22

+0

c#背景.. – Mido 2013-02-17 05:48:12

0

您需要在從數據庫中選擇數據時進行設置。
使用ODER BY ... DESC訂購,LIMIT限制和WHERE過濾掉當前用戶。

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 

}