2013-05-07 52 views
2

我正在檢索數組(僅限ID)的用戶列表,此數組表示用戶之間的連接。這個想法是顯示X個用戶並隱藏其餘的用戶,因此具有頭像設置的用戶是優先考慮的。get_users()包含AND排除

這是我有一個不能正常工作:

// Get all connection id's with avatars 
$members_with_photos = get_users(array('meta_key' => 'profile_avatar', 'include' => $connections)); 

// Shuffle them 
shuffle($members_with_photos); 

// Add the the all_members list 
foreach($members_with_photos as $member_with_photo){ 
    $all_members[] = $member_with_photo->ID; 
} 

// Get all connection id's without avatars 
$members_without_photos = get_users(array('exclude' => $all_members, 'include' => $connections)); 

// Shuffle them 
shuffle($members_without_photos); 

// Also add them to the list 
foreach($members_without_photos as $member_without_photos){ 
    $all_members[] = $member_without_photos->ID; 
} 

的問題是,$ members_without_photos充滿了每一個用戶從$連接陣列。這意味着包含優先排除在上面。

需要做的事情是,get_users()需要從連接中查找用戶,但排除已經找到的用戶(使用頭像),以便沒有頭像的用戶最後會出現在$ all_members數組中。

我現在修復它的方式是在$ all_members數組之後使用array_unique(),但我認爲這更像是一個骯髒的修復。有人可以在這裏指出我正確的方向嗎?

+2

http://core.trac.wordpress.org/ticket/23228 – 2013-08-18 10:18:39

+1

做array_unique上$ all_members是好,因爲它會得到直到他們更新這個.. – 2013-08-18 10:19:50

+0

@ AlexanderKuzmin與WP票證的鏈接就是你的答案。除了構建你自己的'get_users()'版本(例如'gideons_get_users()',而不是調用它)之外別無他法。可能你可以使用PHP的[override_function](http://php.net/manual/en/function.override-function.php)來替換內置的WP函數和你自己的地方,其中包含了票證中的補丁,但我不確定我會100%支持這樣的解決方案,因爲它只比直接修改* wp-includes/user.php *稍微少一些破壞正向兼容性的工作。 – 2015-06-05 11:47:15

回答

0

您可以使用array_diff並計算PHP中的包含列表。這應該給你正在尋找的行爲。與array_diff的代碼中添加:

// Get all connection id's with avatars 
$members_with_photos = get_users(array('meta_key' => 'profile_avatar', 'include' => $connections)); 

// Shuffle them 
shuffle($members_with_photos); 

// Add the the all_members list 
foreach($members_with_photos as $member_with_photo){ 
    $all_members[] = $member_with_photo->ID; 
} 

// Get all connection id's without avatars 
$members_without_photos_ids = array_diff($connections, $all_members); 

$members_without_photos = get_users(array('include' => $members_without_photos_ids)); 

// Shuffle them 
shuffle($members_without_photos); 

// Also add them to the list 
foreach($members_without_photos as $member_without_photos){ 
    $all_members[] = $member_without_photos->ID; 
}