首页 > 后端开发 > php教程 > php数组的排重、累加、排序处理,50分全部送上!解决方法

php数组的排重、累加、排序处理,50分全部送上!解决方法

WBOY
发布: 2016-06-13 13:37:30
原创
900 人浏览过

php数组的排重、累加、排序处理,50分全部送上!

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
$t = array (
  array(
  'cid'  => 123,
  'hits' => 200,
  ),
  array(
  'cid'  => 456,
  'hits' => 100,
  ),
  array(
  'cid'  => 789,
  'hits' => 300,
  ),
  array(
  'cid'  => 123,
  'hits' => 600,
  ),
  array(
  'cid'  => 456,
  'hits' => 500,
  ),
  array(
  'cid'  => 789,
  'hits' => 700,
  ),
);

登录后复制

数组中有很多值是重复的cid,他们对应的hits不一样,希望进行cid排重,hits累加,再按照hits倒序排列,输出结果如下:
PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
$t = array (
  array(
  'cid'  => 789,
  'hits' => 1000,
  ),
  array(
  'cid'  => 123,
  'hits' => 800,
  ),
  array(
  'cid'  => 456,
  'hits' => 600,
  ),
);

登录后复制

多谢大家了!

------解决方案--------------------
PHP code
foreach($t as $v){
     if(!$ar[$v['cid']])
             $ar[$v['cid']]=$v;
     else
             $ar[$v['cid']]['hits']+=$v['hits'];     
}

foreach($ar as $v) $k[]=$v[hits];
array_multisort($k,SORT_DESC,$ar);
print_r($ar);
<br><font color="#e78608">------解决方案--------------------</font><br>
登录后复制
PHP code
$t = array (
  array(
  'cid'  => 123,
  'hits' => 200,
  ),
  array(
  'cid'  => 456,
  'hits' => 100,
  ),
  array(
  'cid'  => 789,
  'hits' => 300,
  ),
  array(
  'cid'  => 123,
  'hits' => 600,
  ),
  array(
  'cid'  => 456,
  'hits' => 500,
  ),
  array(
  'cid'  => 789,
  'hits' => 700,
  ),
);

$r = array();
foreach($t as $v) {
  if(!isset($r[$v['cid']])) $r[$v['cid']] = $v;
  else $r[$v['cid']]['hits'] += $v['hits'];
}

usort($r, create_function('$a,$b', 'return $a["hits"]
                 
              
              
        
            
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板