如何从数组中重复键获取值的总和

时间:2013-12-07 09:27:52

标签: php arrays

我有这些数组:

Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([326] => 20.00)

我想计算一些数量及其相应的总和:

  

265重复4次,其值的总和为36

     

326重复1次,其值的总和为20

感谢您的帮助。

由于

3 个答案:

答案 0 :(得分:1)

$total = array();
foreach($arrays as $array) {
    foreach($array as $key => $value) {
        if (!isset($total[$key])) {
            $total[$key]['hits'] = 0;
            $total[$key]['count'] = 0;
        }

        $total[$key]['hits']++;
        $total[$key]['count']+= $value;
    }
}

答案 1 :(得分:0)

检查此

    <?php
$arr=array(
      array('265'=>'5'),
      array('265'=>'5'),
      array('265'=>'1'),
      array('280'=>'3')
);


$sets = array();
foreach($arr as $array)
{   
   foreach($array as $arrayset=>$cent)
  {

    $sets[$arrayset][] = $cent;

    if(isset($abc[$arrayset])) // prevent index warning
    {           
        $abc[$arrayset] += $cent;
    }
    else
    {
        $abc[$arrayset] = $cent;
    }
  }
}
echo "<pre>";
print_r($abc);

?>

<强>输出

Array
(
    [265] => 11
    [280] => 3
)

答案 2 :(得分:0)

查看我的代码,功能:http://phpfiddle.org/main/code/7ia-40m

$a = array ( array( 265 => '9.00'), array(265 => '9.00'), array(326 => '20.00') );

echo '<pre>'; print_r(getDetails($a)); echo '</pre>';

function getDetails($array) {
    $a = $array;
    $b = array();
    foreach($a as $ar) {
        $n=0;
        foreach($ar as $k => $v) {
            $n++;
            if(isset($b[$k])) {
                $b[$k]['val'] = ($b[$k]['val'] + $v);
                $b[$k]['total']++;
            } else {
                $b[$k]['val'] = (0 + $v);
                $b[$k]['total'] = (1);
            }

        }

    }

    $string = '';
    foreach($b as $k => $arr) {
        $val = $arr['val']; $key = $k; $tot = $arr['total'];
        $string .= $key.' repeated '.$tot.' times. Sum : '.$val.' <br />';
    }

    return $string;

}

结果:

265 repeated 2 times. Sum : 18 
326 repeated 1 times. Sum : 20