【问题标题】:Sort Laravel collection where object is greater than 0 - Laravel 5.2对对象大于 0 的 Laravel 集合进行排序 - Laravel 5.2
【发布时间】:2016-05-16 23:37:59
【问题描述】:

我正在调用 Halo 5 API,特别是获取 Arena 中每个玩家使用的武器。我遇到的问题是,当我拨打电话时,有 7 种武器被玩家击杀 0 次,如下所示:

18 => array:3 [▼
    "WeaponId" => 2457457776.0
    "TotalKills" => 0
    "TotalHeadshots" => 0
  ]
  53 => array:3 [▼
    "WeaponId" => 2015271382
    "TotalKills" => 0
    "TotalHeadshots" => 0
  ]
  51 => array:3 [▶]
  48 => array:3 [▶]
  44 => array:3 [▶]
  27 => array:3 [▶]
  32 => array:3 [▶]

我想从我的收藏中取出这 7 种武器:

我的收藏是这样设置的:

    public function getArenaWeaponKills($playerArenaWeaponStats) {

        $results = collect($playerArenaWeaponStats->Results[0]->Result->ArenaStats->WeaponStats);

        $array = $results->sortByDesc('TotalKills')->map(function($item, $key) {
            return [
                'WeaponId' => $item->WeaponId->StockId,
                'TotalKills'   => $item->TotalKills,
                'TotalHeadshots' => $item->TotalHeadshots,
            ];
        });

        return $array;
    } 

现在我正在按 ('TotalKills') 降序对它们进行排序。有没有办法以相同的方式对它们进行排序包括检查 'TotalKills' 是否 > 然后 0?

【问题讨论】:

    标签: php json laravel collections laravel-5.2


    【解决方案1】:

    你可以在链中添加一个 filter() 方法:

    $array = $results->sortByDesc('TotalKills')
            ->filter(function ($item) {
                return $item->TotalKills > 0;
            })
            ->map(function($item, $key) {
                return [
                    'WeaponId' => $item->WeaponId->StockId,
                    'TotalKills'   => $item->TotalKills,
                    'TotalHeadshots' => $item->TotalHeadshots,
                ];
            });
    

    【讨论】:

    • 非常好的解决方案
    猜你喜欢
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多