Home > database >  collect data in array
collect data in array

Time:10-05

enter image description here

enter image description here

I want to sum the numbers of those with the same category name and I want to print. sample: Edebiyat = 10

CodePudding user response:


// ...


// Handling "grouping" and "summing" operations in "Collection" is much easier.
// Because of this, I convert "array" to "Collection".
$best_selling_categories = collect($best_selling_categories);

// It groups the data by the "category_name" field.
$best_selling_categories = $best_selling_categories->groupBy('category_name');

// It transforms the grouped category list into the sum of the group.
$best_selling_categories = $best_selling_categories->map(function ($categoryGroup){
    return collect($categoryGroup)->sum('number');
});

dd($best_selling_categories);

// Output:
//
// [
//    "Bilgisayar/Tablet" => 7
//    "Çocuk" => 5
//    "Elektronik" => 6
//    "Edebiyat" => 10
// ]

  • Related