FaiChan's avatar

Array Sum

How can I sum the column of the collection in an array? eg. sum all 'kg' of collections

array:5 [▼
  0 => Collection {#796 ▼
    #items: array:1 [▼
      0 => Stock {#794 ▼
        #fillable: array:16 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:19 [▶]
        #original: array:19 [▼
          "id" => 14080
          "in_date" => "2019-02-19"
          "kg" => 0.1
          "height" => 1.0
          "width" => 1.0
          "depth" => 1.0
          "volume" => 0.0
          "location" => "a"
          "order_id" => "T201904010011"
          "out_date" => null
          "group" => 0
          "del" => 0
          "created_at" => "2019-02-19 18:46:46"
          "updated_at" => "2019-02-19 18:46:46"
        ]
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #events: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #guarded: array:1 [▶]
      }
    ]
  }
  1 => Collection {#832 ▼
    #items: array:1 [▶]
  }
  2 => Collection {#868 ▼
    #items: array:1 [▶]
  }
  3 => Collection {#904 ▼
    #items: array:1 [▶]
  }
  4 => Collection {#940 ▼
    #items: array:1 [▶]
  }
] 
0 likes
4 replies
mironmg's avatar

if the collections have the same Class(model) instance you can use eloquent's sum() method

$items = Stock::where('foo','bar')->get();
$total_kg = $items->sum('kg');
lindstrom's avatar

Might as well get straight to the point:

$total_kg = Stock::where('foo', 'bar')->sum('kg');
FaiChan's avatar
foreach ($request->stockid as $key => $value){
       $stocks[] = Stock::where('id', $value)->get();
      }

the array is getting from foreach result. how can I sum it in an easy way? thanks!

lindstrom's avatar
Level 15

So $request->stockid is an array of stock id's? Once you have built up your array, just collect and sum the array:

$stocks = [
    [
        'id' => 1,
        'kg' => 10,
    ],
    [
        'id' => 2,
        'kg' => 20,
    ],
    [
        'id' => 3,
        'kg' => 30,
    ],
];

$total_kg = collect($stocks)->sum('kg');

See: https://implode.io/ajr9a1

Alternatively, if you don't need to build up the array with other values and, again, that $request->stockid is an array of stock id's:

$total_kg = Stock::whereIn('id', $request->stockid)->sum('kg');

Please or to participate in this conversation.