【问题标题】:Remove duplicates from multi-dimensional array based on higher points基于较高点从多维数组中删除重复项
【发布时间】:2009-11-01 14:10:54
【问题描述】:

我绞尽脑汁想出一个解决方案。我可以找到很多解决方案来从二维数组中删除重复值,但我需要删除值低于另一个值的重复值。这是数组:

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循环会更合适,但我不知道要测试什么条件。

有什么想法吗?!

【问题讨论】:

  • 为什么要连续循环?通过一行并同时查找另一行中的每个条目似乎就足够了。如果您发现重复项,则删除分数较低的那个。当然,因为两个索引都发生了变化,所以你必须维护一个从 0 开始的独立索引。while 条件将是“当前第一个数组索引小于第一个数组长度”。只有在给定步骤没有删除第一个数组中的元素时,才增加索引。
  • 这只是一个例子,在我的实际场景中有超过两行(100 行)。

标签: php arrays


【解决方案1】:

我将遍历您的数据并创建一个字典,其中键是用户 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...

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2017-05-19
    • 2017-01-01
    • 2014-05-26
    • 2012-12-14
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多