Skip to content

Instantly share code, notes, and snippets.

@dcb9
Created January 17, 2015 16:27
Show Gist options
  • Save dcb9/f04613a6f286f795353e to your computer and use it in GitHub Desktop.
Save dcb9/f04613a6f286f795353e to your computer and use it in GitHub Desktop.
<?php
# filepath src/
class MyArray
{
public static function sumCountByIdentity($items, $identityKey, $countKey){
$tmp = $newItems = [];
foreach($items as $row){
if( ! is_array($row) || !isset($row[$identityKey]) || !isset($row[$countKey]) ){
throw new InvalidArgumentException('sub value of items must an array');
}
if( ! array_key_exists($row[$identityKey], $tmp) ){
$tmp[$row[$identityKey]] = 0;
}
$tmp[$row[$identityKey]] += $row[$countKey];
}
foreach($tmp as $address => $count){
$newItems[] = [ $identityKey => $address, $countKey => $count, ];
}
return $newItems;
}
}
<?php
# filepath tests/
include ('../src/Array.php');
class ArrayTest extends PHPUnit_Framework_TestCase
{
public $items = array(
array("address"=>"美国", "count"=>123),
array("address"=>"美国", "count"=>34),
array("address"=>"中国", "count"=>2),
array("address"=>"中国", "count"=>20),
array("address"=>"法国", "count"=>345)
);
public $exceptValues = [ '美国' => 157, '法国' => 345, '中国' => 22, ];
public function testSumCountByIdentity(){
$data = MyArray::sumCountByIdentity( $this->items, 'address', 'count');
foreach($data as $row){
$address = $row['address'];
$count = $row['count'];
$this->assertEquals($this->exceptValues[$address], $count);
}
}
/**
* @expectedException InvalidArgumentException
*/
public function testSumCountByIdentityException1(){
$arr = $this->items;
$arr[] = "";
MyArray::sumCountByIdentity($arr, 'address', 'count');
}
/**
* @expectedException InvalidArgumentException
*/
public function testSumCountByIdentityException2(){
MyArray::sumCountByIdentity($this->items, 'address', 'ss');
}
/**
* @expectedException InvalidArgumentException
*/
public function testSumCountByIdentityException3(){
MyArray::sumCountByIdentity($this->items, 'aaa', 'count');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment