如何对数组求和并求和? [英] How to Group by and take sum in array?

查看:136
本文介绍了如何对数组求和并求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按part_no分组,最后显示带销售总额的部件号.

I want to Group by part_no and in the end it show part number with sum of sale.

Array
(
    [0] => Array
        (
            [part_no] => 04152-yzza4
            [sale_qty] => 1
        )
[1] => Array
    (
        [part_no] => 04465-YZZR3
        [sale_qty] => 12
    )

[2] => Array
    (
        [part_no] => 04152-yzza1
        [sale_qty] => 3
    )

[3] => Array
    (
        [part_no] => 04465-YZZR3
        [sale_qty] => 1
    )

[4] => Array
    (
        [part_no] => 04465-YZZR3
        [sale_qty] => 1
        )

)

输出应为:

04152-yzza4:1

04152-yzza4 : 1

04465-YZZR3:14

04465-YZZR3 :14

04152-yzza1:3

04152-yzza1 : 3

我尝试过函数和类,但对我没有任何帮助,请帮忙

I tried function and classes but nothing work for me, please help

推荐答案

一个简单的foreach循环可以做到这一点:

A simple foreach loop can do that:

https://3v4l.org/1dfov

<?php

$input = [
    ['part_no'=>'test1','sale_qty' => 4],
    ['part_no'=>'test1','sale_qty' => 2],
    ['part_no'=>'test2','sale_qty' => 1],
    ['part_no'=>'test3','sale_qty' => 3],
];


$output = [];
foreach($input as $i) {
    if(!isset($output[$i['part_no']])) {
        $output[$i['part_no']] = 0;    
    }

    $output[$i['part_no']] += $i['sale_qty'];
}
var_dump($output);

输出

array(3){ ["test1"] => 整数(6) ["test2"] => 整数(1) ["test3"] => 整数(3) }

array(3) { ["test1"]=> int(6) ["test2"]=> int(1) ["test3"]=> int(3) }

参考文献:

http://php.net/manual/en/control-structures .foreach.php

这篇关于如何对数组求和并求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆