我正在检索数组中的用户列表(仅限id),此数组表示用户之间的连接。我们的想法是显示X用户并隐藏其余用户,因此设置头像的用户是首要任务。
这就是我无法正常工作的原因:
// 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充满了$ connections数组中的每个用户。这意味着包含优先于排除。
需要发生的是get_users()需要从连接中查找用户,但排除已找到的用户(带有头像),以便没有头像的用户最后会出现在$ all_members数组中。
我现在修复它的方法是在$ all_members数组之后使用array_unique(),但我认为这更像是一个脏修复。有人能指出我在正确的方向吗?
答案 0 :(得分: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;
}