您的位置:首页 > 编程语言 > PHP开发

PHP之数据分组

2016-02-17 17:06 555 查看
今天公司需求要做统计,而且是要相同单位的加在一起,好吧,起初以为很简单,后来就费劲的,因为单位不止一两个,这就需要分组,然后进行统计……

我把那些数据抽离,单独放到一个数组中,如图


然后就需要分组了,话不多说,上代码,

/*
$array是传入的数据(数组格式)
$unset是要销毁的键
$max是要统计的数据
*/
function unit_sum($array,$unset,$max){
$items = array();
$result=array();
$product_num=array();
foreach($array as $item) {
$unit = $item[$unset];
unset($item[$unset]);
if(!isset($items[$unit])) {
$items[$unit] = array($unset=>$unit, 'items'=>array());
}
$items[$unit]['items'][] = $item;
}
foreach ($items as $k => $v) {
if($k==''){
unset($items[$k]);
}
foreach ($v['items'] as $key => $value) {
$result[$k]+=$value[$max];
if($k==''){
unset($result[$k]);
}
}
}
$i=0;
foreach ($result as $key => $value) {
if($i!=count($result)-1){
$product_num[]=$value.$key.'|';
}else{
$product_num[]=$value.$key;
}
$i++;
}
return $product_num;
}


打印数据看一下,好的,就是酱紫…………

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息