相同产品的Sum数组值

问题描述 投票:-6回答:2

我有以下类型的数组。 如何从输入数组中获得所需的输出。 注意:数组是dynamaic 想要使用相同的product_id对comp_size求和。提前致谢。 输入数组

array:4 [
  0 => array:3 [
    "comp_size" => "4.5"
    "comp_id" => "10"
    "product_id" => "1"
  ]
  1 => array:3 [
    "comp_size" => "4.5"
    "comp_id" => "11"
    "product_id" => "2"
  ]
  2 => array:3 [
    "comp_size" => "4.5"
    "comp_id" => "12"
    "product_id" => "2"
  ]
  3 => array:3 [
    "comp_size" => "4.5"
    "comp_id" => "13"
    "product_id" => "2"
  ]
]

期望的结果:

[
    0 => array [
        product_id => 1
        total_size => 4.5
    ]
    1 => array[
        product_id => 2
        total_size => 13.5
    ]
]
php arrays laravel laravel-5
2个回答
0
投票

你可以使用Laravel的groupBymapCollection函数来做到这一点:

$collection = new \Illuminate\Support\Collection($array);
$group = $collection->groupBy('product_id');
$resultArray = $group->map(function($item, $key) {
            return [
                'total_size' => $item->sum('comp_size'),
                'product_id' => $key,
            ];
        });

这将使您将来可以更轻松地扩展代码。


0
投票

试试这个,循环遍历数组的所有元素,总结大小值:

<?php

$data = [] // original array;
$sum  = [] // result;

foreach ($data as $dt) {
    if (!isset($sum[$dt['product_id']])) {
        $sum[$dt['product_id']] = 0;
    }

    $sum[$dt['product_id']] += $dt['comp_size'];
}

?>
© www.soinside.com 2019 - 2024. All rights reserved.