Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created May 17, 2012 19:02
Show Gist options
  • Save mlconnor/2720928 to your computer and use it in GitHub Desktop.
Save mlconnor/2720928 to your computer and use it in GitHub Desktop.
A php class that allows you to do functions across arrays of objects or arrays
$am = new ArrayMath();
$am->options = array('a'=>'sum', 'b'=>'avg', 'c'=>'max', 'd'=>'min', 'e'=>'prod');
$result = array(
array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>5, 'e'=>2),
array('a'=>2, 'b'=>3, 'c'=>4, 'd'=>6, 'e'=>3),
array('a'=>3, 'b'=>4, 'c'=>0, 'd'=>7, 'e'=>4)
);
print_r($am->run($result));
/* RETURNS
stdClass Object
(
[a] => 6
[b] => 3
[c] => 4
[d] => 5
[e] => 24
)
*/
class ArrayMath {
public $options;
public $calls;
function __construct() {
$calls = array(
'sum' => array('walk' => function($val, $curr) { return $curr + $val; }),
'avg' => array('first' => function($val) { return array('count'=>1, 'sum'=>$val); },
'walk' => function($val, $curr) { $curr['count']++; $curr['sum'] += $val; return $curr; },
'last' => function($val, $curr) { $curr['sum'] += $val; $curr['count']++; return $curr['sum'] / $curr['count'];} ),
'max' => array('walk' => function($val, $curr) { return max($curr, $val); }),
'min' => array('walk' => function($val, $curr) { return min($curr, $val); }),
'prod' => array('walk' => function($val, $curr) { return $curr * $val; })
);
$this->calls = $calls;
}
public function run($input) {
if ( ! is_array($input) ) throw new Exception('input must be an array');
$result = new stdclass;
print_r($this->options);
foreach ($input as $index => $entry) {
if ( is_array($entry) ) {
$entry = (object) $entry;
}
foreach ($this->options as $prop => $call) {
$fns = $this->calls[$call];
if ( isset($entry->$prop) ) {
$value = $entry->$prop;
$func = $fns['walk'];
if ( $index == 0 ) {
$func = isset($fns['first']) ? $fns['first'] : function($val) { return $val; };
} else if ( $index == count($input) - 1 && isset($fns['last']) ) {
$func = $fns['last'];
}
$result->$prop = $func($value, isset($result->$prop) ? $result->$prop : null);
}
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment