作者:天涯使者2602921991 | 来源:互联网 | 2014-06-17 17:22
如题,如果是从数据库里取数据的时候大可以使用如下SQLSELECTSUM(t_value),t_idFROMt_tableGROUPBYt_id但是如果是在php程序中处
如题,如果是从数据库里取数据的时候大可以使用如下SQL
SELECT SUM(t_value),t_id FROM t_table GROUP BY t_id
但是如果是在php程序中处理类似的问题就稍微麻烦点了,这里给个函数就是处理类似的问题,实例代码如下:
-
-
-
- function add_array($arr, &$new_arr, $target_key) {
- $num = count($new_arr);
- for ($i = 0; $i < $num; $i++) {
-
-
-
-
- if ($arr[$target_key] != $new_arr[$i][$target_key]) {
- $cmp_num++;
- } else {
- $tar_exist = true;
- $tar_key = $i;
- break;
- }
- }
-
- if ($cmp_num == $num)
- $tar_exist = false;
- if ($tar_exist) {
- foreach ($arr as $key => $value) {
- if ($key != $target_key) {
- $new_arr[$tar_key][$key]+=$value;
- }
- }
- } else {
-
-
-
-
-
- $new_arr[$num][$target_key] = $arr[$target_key];
- foreach ($arr as $key => $value) {
- if ($key != $target_key) {
- $new_arr[$num][$key]+=$value;
- }
- }
- }
- }
- $arr = array(
- array(&#39;group_id&#39; => 13, &#39;team_price&#39; => 88.00, &#39;satopay_price&#39; => 85.00, &#39;team_id&#39; => 348, &#39;origin&#39; => 440, &#39;gain&#39; => 14.45, &#39;quantity&#39; => 5),
- array(&#39;group_id&#39; => 13, &#39;team_price&#39; => 12.00, &#39;satopay_price&#39; => 11.00, &#39;team_id&#39; => 344, &#39;origin&#39; => 36, &#39;gain&#39; => 2.76, &#39;quantity&#39; => 3),
- array(&#39;group_id&#39; => 14, &#39;team_price&#39; => 4.99, &#39;satopay_price&#39; => 4.60, &#39;team_id&#39; => 335, &#39;origin&#39; => 4.99, &#39;gain&#39; => 0.31915, &#39;quantity&#39; => 1),
- array(&#39;group_id&#39; => 14, &#39;team_price&#39; => 12.00, &#39;satopay_price&#39; => 11.00, &#39;team_id&#39; => 344, &#39;origin&#39; => 24, &#39;gain&#39; => 1.84, &#39;quantity&#39; => 2),
- array(&#39;group_id&#39; => 15, &#39;team_price&#39; => 13.00, &#39;satopay_price&#39; => 11.00, &#39;team_id&#39; => 344, &#39;origin&#39; => 24, &#39;gain&#39; => 1.84, &#39;quantity&#39; => 2),
- );
- $new_arr = array();
- foreach ($arr as $key => $value) {
- add_array($value, &$new_arr, &#39;group_id&#39;);
- }
- var_dump($new_arr);