代码之家  ›  专栏  ›  技术社区  ›  Jaquarh

在按其他键排序之前,如何按键对PHP数组进行分组?

  •  -1
  • Jaquarh  · 技术社区  · 4 年前

    我有一个包含密钥的数组 counted placement 在分类之前,我试图对其进行分组。数组应首先按 计数 然后,对于每个副本 ,然后应按 安置 .

    $array = [
        [
            'id' => 1,
            'placement' => 8,
            'counted' => 3
            'user' => ['name' => 'foo'],
        ],
        [
            'id' => 2,
            'placement' => 5,
            'counted' => 3
            'user' => ['name' => 'bar'],
        ],
        [
            'id' => 3,
            'placement' => 1,
            'counted' => 2
            'user' => ['name' => 'foobar'],
        ]
    ];
    

    我在这里的预期输出是:

    $array = [
        [
            'id' => 2,
            'placement' => 5,
            'counted' => 3
            'user' => ['name' => 'bar'],
        ],
        [
            'id' => 1,
            'placement' => 8,
            'counted' => 3
            'user' => ['name' => 'foo'],
        ],
        [
            'id' => 3,
            'placement' => 1,
            'counted' => 2
            'user' => ['name' => 'foobar'],
        ]
    ];
    

    我已经试过了 usort 为实现这一目标:

    usort($array, fn($a, $b) => ((int)$a['placement'] <=> (int)$b['counted']) * -1);
    

    2 回复  |  直到 4 年前
        1
  •  2
  •   Hung Pham    4 年前

    因为你更喜欢使用usort,所以这是我的答案

    $array = [
        [
            'id' => 1,
            'placement' => 8,
            'counted' => 3,
            'user' => ['name' => 'foo'],
        ],
        [
            'id' => 2,
            'placement' => 5,
            'counted' => 3,
            'user' => ['name' => 'bar'],
        ],
        [
            'id' => 3,
            'placement' => 1,
            'counted' => 2,
            'user' => ['name' => 'foobar'],
        ]
    ];
    
    
    usort($array, function ($a, $b) {
        if ($a['counted'] < $b['counted']) {
            return 1;
        }
    
        if ($a['counted'] === $b['counted'] && $a['placement'] > $b['placement']) {
            return 1;
        }
    });
    
        2
  •  1
  •   rubys    4 年前

    如果你不在乎效率,你可以这样写

    collect($array)
        ->sortByDesc('counted')
        ->groupBy('counted')
        ->map(function ($group) {
            return $group->sortBy('placement');
        })
        ->flatten(1)
        ->toArray()
    
    推荐文章