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

问题描述

如何使用evaluation_category_id

Array
(
 [0] => Array
    (
        [id] => 60
        [evaluation_category_id] => 3
        [score] => 15
        [itemMaxPoint] => 20
    )
 [1] => Array
    (
        [id] => 61
        [evaluation_category_id] => 2
        [score] => 10
        [itemMaxPoint] => 20
    )

 [2] => Array
    (
        [id] => 62
        [evaluation_category_id] => 1
        [score] => 5
        [itemMaxPoint] => 20
    )

  [3] => Array
    (
        [id] => 63
        [evaluation_category_id] => 1
        [score] => 50
        [itemMaxPoint] => 200
    )

  [4] => Array
    (
        [id] => 64
        [evaluation_category_id] => 2
        [score] => 150
        [itemMaxPoint] => 200
    )

  [5] => Array
    (
        [id] => 65
        [evaluation_category_id] => 3
        [score] => 30
        [itemMaxPoint] => 50
    )
    .
    .
    .
 )

这样我就可以得到这样的数组

So that i get array like this

 Array
  (
   [0] => Array
      (

    [evaluation_category_id] => 3
    [score] => 45
    [itemMaxPoint] => 70
   )

   [1] => Array
      (
    [evaluation_category_id] => 2
    [score] => 160
    [itemMaxPoint] => 220
   )

   [2] => Array
      (
    [evaluation_category_id] => 1
    [score] => 55
    [itemMaxPoint] => 220
   )
} 

我已经尝试过了,但是没有用.请纠正我做错了的地方

i have tried this but its not working .please correct me where i am doing wrong

 public function test($data) {
    $groups = array();
    foreach ($data as $item) {
        $key = $item['evaluation_category_id'];
        if (!isset($groups[$key])) {
            $groups[$key] = array(
                'id' => $key,
                'score' => $item['score'],
                'itemMaxPoint' => $item['itemMaxPoint'],
            );
        } else {
            $groups[$key]['score'] = $groups[$key]['score'] + $item['score'];
            $groups[$key]['itemMaxPoint'] = $groups[$key]['itemMaxPoint'] +$item['itemMaxPoint'];
        }
    }
    return $groups;
}

输出为

Array
(
 [2] => Array
    (
        [id] => 2
        [score] => 121 //121 because the given array is different.but its actually SUM all values of score
        [itemMaxPoint] => 300
    )

)

推荐答案

我已经解决了.

public function getDateWiseScore($data) {
    $groups = array();
    foreach ($data as $item) {
        $key = $item['evaluation_category_id'];
        if (!array_key_exists($key, $groups)) {
            $groups[$key] = array(
                'id' => $item['evaluation_category_id'],
                'score' => $item['score'],
                'itemMaxPoint' => $item['itemMaxPoint'],
            );
        } else {
            $groups[$key]['score'] = $groups[$key]['score'] + $item['score'];
            $groups[$key]['itemMaxPoint'] = $groups[$key]['itemMaxPoint'] + $item['itemMaxPoint'];
        }
    }
    return $groups;
}

这篇关于如何使用GROUP BY和SUM PHP数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:14