[英]Remove duplicates from multi-dimensional array based on higher points
我絞盡腦汁想想辦法。 我可以找到很多解決方案來從2d數組中刪除重復對象,但是我需要刪除值低於另一個對象的重復對象。 這是數組:
Array
(
[basketball] => Array
(
[0] => stdClass Object
(
[id] => 2
[username] => Beans
[points] => 30
)
[1] => stdClass Object
(
[id] => 314
[username] => slights
[points] => 20
)
[2] => stdClass Object
(
[id] => 123
[username] => gibb54
[points] => 5
)
)
[soccer] => Array
(
[0] => stdClass Object
(
[id] => 2
[username] => Beans
[points] => 95
)
[1] => stdClass Object
(
[id] => 49
[username] => sans
[points] => 65
)
[2] => stdClass Object
(
[id] => 122
[username] => peano
[points] => 50
)
[3] => stdClass Object
(
[id] => 174
[username] => fordb
[points] => 30
)
[4] => stdClass Object
(
[id] => 112
[username] => danc
[points] => 30
)
)
)
如您所見,用戶ID 2,Beans是籃球和足球的首選。 由於他們的足球得分更高,因此我需要刪除他們的籃球條目,以使ID 314變為0。
我將需要連續執行此操作,直到沒有任何用戶兩次將任何主數組值設為0為止。
我已經嘗試過foreach解決方案的各種組合,但是我一無所獲。 我以為使用while循環會更合適,但我不知道要測試什么條件。
有什么想法嗎?
我將遍歷您的數據並創建一個字典,其中的鍵是用戶ID,值是附加了運動的適當的用戶對象。 然后,您可以使用體育數據通過遍歷此重復數據刪除的數組來確定每個用戶的放置位置,從而重構示例數據數組結構。
要創建重復數據刪除數組,請使用類似以下內容的方法:
$deDupedData = array();
foreach ($data as $sport => $users) {
foreach ($users as $user) {
if (isset($deDupedData[$user->id])) {
if ($user->points > $deDupedData[$user->id]->points) {
$deDupedData[$user->id]->sport = $sport;
$deDupedData[$user->id]->points = $user->points;
}
} else {
$modifiedUser = $user;
$modifiedUser->sport = $sport;
$deDupedData[$user->id] = $modifiedUser;
}
}
}
// Now reconstruct your array...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.