对象大于0的Laravel集合排序 - Laravel 5.2

时间:2016-05-16 23:38:00

标签: php json laravel collections laravel-5.2

我打电话给Halo 5 API,特别是让竞技场中的每个玩家使用武器。我遇到的问题是,当我拨打电话时,有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?

1 个答案:

答案 0 :(得分:4)

您可以在链中添加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,
            ];
        });