The sorting, adding, and sorting of php arrays are delivered at 50 points! PHPcode $ t = array ('CID' = & gt; 123, 'hits '= & gt; 200,), array ('CID' = & gt; 456, 'hits '= & gt; 100, sorting, adding, and sorting of php arrays, all delivered at 50 points!
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, ),);
There are many repeated CIDs in the array. their corresponding hits is different. we want to sort the CIDs in descending order and accumulate the hits. the output result is as follows:
PHP code
$t = array ( array( 'cid' => 789, 'hits' => 1000, ), array( 'cid' => 123, 'hits' => 800, ), array( 'cid' => 456, 'hits' => 600, ),);
Thank you!
------ Solution --------------------
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 );
------ Solution --------------------
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"]<$b["hits"];'));print_r($r);