mardi 4 décembre 2018

Diffrentiate Array base on Value And Sum Of Array in Laravel

I have array and first of all i want to diffrentiate base on site(key) and site is not limited to 1 or 2 And then sum of opening balance and closing balance of site like all site(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
    }, 

And I want ouput is

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

And Code I tried

{
    $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;
        }*/
}

after this code which i commented output is but then i dont know how sum of this

{
"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,



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zHOxOr
via IFTTT

Aucun commentaire:

Enregistrer un commentaire