Created
November 7, 2017 20:48
-
-
Save masterfermin02/b1fd4953272c5a011591d94fc88b4b56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$data = json_decode('[ | |
{ | |
"id": 1, | |
"value1": 5, | |
"value2": 10 | |
}, | |
{ | |
"id": 2, | |
"value1": 50, | |
"value2": 100 | |
}, | |
{ | |
"id": 1, | |
"value1": 1, | |
"value2": 2 | |
}, | |
{ | |
"id": 2, | |
"value1": 15, | |
"value2": 20 | |
}, | |
{ | |
"id": 3, | |
"value1": 15, | |
"value2": 20 | |
} | |
]'); | |
//print_r(array_group_by($data,'id')); | |
print_r(array_sum_by($data,'id',['value1','value2'])); | |
//print_r(array_sum(array_column($data,'value1'))); | |
function array_sum_by($array,$group,$keys) | |
{ | |
$groupeddata = array_group_by($array,$group); | |
return array_map(function($items) use($group,$keys) { | |
foreach($keys as $key) | |
{ | |
$values[$key] = array_sum(array_column($items,$key)); | |
} | |
$first = array_shift($items); | |
if(is_object( $first ) && isset( $first->{ $group } )){ | |
$values = array_merge([ $group => $first->{ $group } ], $values); | |
}elseif(isset($first[$group])){ | |
$values = array_merge([ $group => $first[$group] ], $values); | |
} | |
return $values; | |
},$groupeddata); | |
} | |
function array_group_by( array $array, $key ) | |
{ | |
if ( ! is_string( $key ) && ! is_int( $key ) && ! is_float( $key ) && ! is_callable( $key ) ) { | |
trigger_error( 'array_group_by(): The key should be a string, an integer, or a callback', E_USER_ERROR ); | |
return null; | |
} | |
$func = ( is_callable( $key ) ? $key : null ); | |
$_key = $key; | |
// Load the new array, splitting by the target key | |
$grouped = []; | |
foreach ( $array as $value ) { | |
if ( is_callable( $func ) ) { | |
$key = call_user_func( $func, $value ); | |
} elseif ( is_object( $value ) && isset( $value->{ $_key } ) ) { | |
$key = $value->{ $_key }; | |
} elseif ( isset( $value[ $_key ] ) ) { | |
$key = $value[ $_key ]; | |
} else { | |
continue; | |
} | |
$grouped[ $key ][] = $value; | |
} | |
// Recursively build a nested grouping if more parameters are supplied | |
// Each grouped array value is grouped according to the next sequential key | |
if ( func_num_args() > 2 ) { | |
$args = func_get_args(); | |
foreach ( $grouped as $key => $value ) { | |
$params = array_merge( [ $value ], array_slice( $args, 2, func_num_args() ) ); | |
$grouped[ $key ] = call_user_func_array( 'array_group_by', $params ); | |
} | |
} | |
return $grouped; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment