从多维数组中计算值

时间:2014-06-04 16:47:14

标签: php arrays

我有阵列: -

Array
(
[id] => 1
[aid] => 2
[views] => 1731
)

Array
(
[id] => 3
[aid] => 2
  [views] => 4421
)

Array
(
[id] => 1
[aid] => 1
[views] => 6136
)

我有上面的数组我希望显示相同的键和总视图

$aidArray=array();

foreach($data as $key=>$row){
   // creating array for aid
   if(!in_array($row['aid'], $aidArray)){
   $aidArray[] = $row['aid'];
}

}

上面的数组返回

Array
(
[0] => 1
[1] => 3
)

我还想计算“观看次数”的总和。对于每一个相同的援助。

1 个答案:

答案 0 :(得分:0)

使用PHP 5.5 array_column()

$myArray = array(
    array( 'id' => 1, 'aid' => 2, 'cid' => 3, 'sid' => 1, 'tid' => 100000, 'views' => 1731 ),
    array( 'id' => 2, 'aid' => 2, 'cid' => 4, 'sid' => 1, 'tid' => 100000, 'views' => 4421 ),
    array( 'id' => 3, 'aid' => 1, 'cid' => 7, 'sid' => 3, 'tid' => 100001, 'views' => 6136 ),
);

$aidArray = array();
foreach(array_unique(array_column($myArray,'aid')) as $aid) {
    $aidArray[$aid] = array_sum(array_column(
        array_filter(
            $myArray,
            function($value) use ($aid) {
               return $value['aid'] == $aid;
            }
        ),
        'views'
    ));
}

var_dump($aidArray);

给出

array(2) {
  [2]=>
  int(6152)
  [1]=>
  int(6136)
}

修改

对于5.5之前的PHP版本(使用闭包,因此需要> = 5.3)

$aidArray = array();
foreach(array_unique(array_map(function($value) {return $value['aid']; }, $myArray)) as $aid) {
    $aidArray[$aid] = array_sum(array_map(
        function($value) {return $value['views']; },
        array_filter(
            $myArray,
            function($value) use ($aid) {
               return $value['aid'] == $aid;
            }
        )
    ));
}