根据 Laravel 中数组的值和总和区分数组

Differentiate Array base on Value And Sum Of Array in Laravel

我有数组,首先我想根据站点(键)进行区分,站点不限于 1 或 2 然后是站点的期初余额和期末余额之和 像所有网站(888) total_balance = opening_balance + closing_balance (999) total_balance = opening_balance + closing_balance

"games": [
    {
        "id": 240,
        "user_id": 1,
        "site": "888",
        "opening_balance": 5,
        "closing_balance": 6
    },
    {
        "id": 243,
        "user_id": 1,
        "site": "999",
        "opening_balance": 3,
        "closing_balance": 4
    },
    {
        "id": 244,
        "user_id": 1,
        "site": "888",
        "opening_balance": 5,
        "closing_balance": 6
    }, 

并且想要像这样的输出 (站点 => 888,total_balance => 22,站点 => 999,total_balance => 7 (它可以是 b 字符串))

我试过的代码:

{
    $collection = collect(Site::all())->map(function($item , $key){
                            return $item["name"];
                        });

    $record = Game::whereIn('site',$collection)->get();
    dd($record);

    /*$bySite = array();
        foreach ($record as $key => $item) {
            if(!isset($bySite[$item['site']])) {
                $bySite[$item['site']] = array();
            }
            $bySite[$item['site']][$key] = $item;
        }*/
}

在我评论输出的这段代码之后 但我不知道这个

的总和
{
"888": {
    "0": {
        "id": 240,
        "user_id": 1,
        "site": "888",
        "opening_balance": 5,
        "closing_balance": 6
    },
   "2": {
        "id": 244,
        "user_id": 1,
        "site": "888",
        "opening_balance": 5,
        "closing_balance": 6
    },
  },
"999": {
    "1": {
        "id": 243,
        "user_id": 1,
        "site": "999",
        "opening_balance": 3,
        "closing_balance": 4,

您可以使用 Laravel 集合实现此目的。

$games =  [
    [
        "id" =>  240,
        "user_id" =>  1,
        "site" =>  "888",
        "opening_balance" =>  5,
        "closing_balance" =>  6
    ],
    [
        "id" =>  243,
        "user_id" =>  1,
        "site" =>  "999",
        "opening_balance" =>  3,
        "closing_balance" =>  4
    ],
    [
        "id" =>  244,
        "user_id" =>  1,
        "site" =>  "888",
        "opening_balance" =>  5,
        "closing_balance" =>  6
    ]
];

$games = collect($games);

$games = $games->groupBy('site')->map(function($game, $key){
    return [
        'site' => $key,
        'total_balance' => $game->sum('opening_balance') + $game->sum('closing_balance'),
    ];
})->values();

dd($games->toArray());

输出将是,

array:2 [▼
    0 => array:2 [▼
        "site" => 888
        "total_balance" => 22
    ]
    1 => array:2 [▼
        "site" => 999
        "total_balance" => 7
    ]
]

代码段:https://implode.io/5aPGeH

步 1.foreach($集合) 2. 将值求和并存储在数组中,如 $collection->sum('opening_balance'), ($collection->sum('closing_balance') 3.然后对变量求和 4.停止循环 5. 然后 $final = $final['site'] 。 “=>”。 $最终['sum'];