【问题标题】:Sum array values of the same product对同一产品的数组值求和
【发布时间】:2018-06-05 01:30:58
【问题描述】:

我有以下类型的array
如何从输入array 获得所需的输出。
注意:array 是动态的
想要comp_size 与相同product_id 的总和。在此先感谢。
输入数组

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
    ]
]

【问题讨论】:

  • 你的意思是mysql查询总和还是数组总和?
  • @EtibarRustemzade 是的,输入数组来自 mysql,我想要这个数组根据所需的数组
  • 你考虑过遍历数组吗?并对值求和?

标签: php arrays laravel laravel-5


【解决方案1】:

试试这个,遍历数组的所有元素,对大小值求和:

<?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'];
}

?>

【讨论】:

  • 谢谢@cludio
【解决方案2】:

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

$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,
            ];
        });

这将使您将来更容易扩展代码。

【讨论】:

  • 非常感谢
猜你喜欢
  • 2018-11-23
  • 2013-01-09
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多