PHP总结两个键具有相同值的数组条目 [英] PHP sum up array entries where two keys have the same value

查看:117
本文介绍了PHP总结两个键具有相同值的数组条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组,其中我想对源和目标相同的所有条目的total_volume求和。

I have the following array, in which I want to sum up the total_volume for all entries where the source and the target are the same.

Array (
[0] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 10
    )

[1] => Array
    (
        [source] => ABC
        [target] => GHI
        [total_volume] => 5
    )
[2] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 5
    )
)

结果数组应如下所示:

ResultArray (
[0] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 15
    )

[1] => Array
    (
        [source] => ABC
        [target] => GHI
        [total_volume] => 5
    )
)

我首先想到的是通过现有数组,并通过ResultArray上的嵌套循环检查是否已存在具有匹配的源-目标对的条目。

My first thought would be to llop through the existing array and check via a nested loop over the ResultArray whether an entry with the matching source-target-pair already exists.

还有另一种使用array_walk()或

Is there an other way using array_walk() or a similar method?

提前感谢您的帮助!

推荐答案

不是很漂亮,但是这里是我如何使用嵌套的foreach来做到这一点;

not pretty but heres how I would do it with a nested foreach;

$aStartingArray = array();
$aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 10); 
$aStartingArray[] = array('source'=>'ABC', 'target' => 'GHI', 'total_volume' => 5); 
$aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 5); 


$aSortedArray = array();

foreach ($aStartingArray as $aArray) {

    $bSet = false;

    foreach ($aSortedArray as $iPos => $aTempSortedArray) {

        if(
            $aTempSortedArray['source'] == $aArray['source'] && 
            $aTempSortedArray['target'] == $aArray['target']){

            $aSortedArray[$iPos]['total_volume'] += $aArray['total_volume'];

            $bSet = true;
        }

    }

    if(!$bSet) {

        $aSortedArray[] = array(
            'source' => $aArray['source'], 
            'target' => $aArray['target'], 
            'total_volume' => $aArray['total_volume']
            );
    }
}


var_dump($aSortedArray);

这篇关于PHP总结两个键具有相同值的数组条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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