$users = [
['id' => 1, 'gender' => 'M', 'dob' => 1990, 'country' => 'IN', 'activity_score' => 34],
['id' => 2, 'gender' => 'M', 'dob' => 1980, 'country' => 'US', 'activity_score' => 9],
['id' => 3, 'gender' => 'F', 'dob' => 1993, 'country' => 'UK', 'activity_score' => 45],
['id' => 4, 'gender' => 'M', 'dob' => 1998, 'country' => 'IN', 'activity_score' => 0],
['id' => 5, 'gender' => 'F', 'dob' => 1997, 'country' => 'IN', 'activity_score' => 234],
['id' => 6, 'gender' => 'M', 'dob' => 1991, 'country' => 'UK', 'activity_score' => -6],
['id' => 7, 'gender' => 'F', 'dob' => 1992, 'country' => 'JP', 'activity_score' => 9],
['id' => 8, 'gender' => 'M', 'dob' => 1998, 'country' => 'US', 'activity_score' => 45],
['id' => 9, 'gender' => 'F', 'dob' => 2000, 'country' => 'JP', 'activity_score' => 5],
['id' => 10, 'gender' => 'M', 'dob' => 2006, 'country' => 'IN', 'activity_score' => 7],
['id' => 11, 'gender' => 'F', 'dob' => 1970, 'country' => 'US', 'activity_score' => 32],
['id' => 12, 'gender' => 'M', 'dob' => 2011, 'country' => 'IN', 'activity_score' => 21],
];
$act_sum=0;
$act_sum1=0;
foreach($users as $user){
$age=date('Y')-$user['dob'];
if($age>=16&& $age<=20)
{
$act_sum+=$user['activity_score'];
}
else if($age>20){
$act_sum1+=$user['activity_score'];
}
}
without these if condition can it be possible by array functions itself? i have to find Sum activity score by age group 16-20, 20+
Try this maybe :
// Your result array with score by age group
$result = array(
'16-20' => 0,
'20+' => 0
);
// The current year
$current_year = date('Y');
// Loop throught users
foreach ($users as $user) {
// I calcul the age of the user according to current_year
$age = $current_year - $user['dob'];
// If $user age is 16, 17, 18 or 19, I add his score
if ($age < 20 && $age >= 16) {
$result['16-20'] = $result['16-20'] + $user['activity_score'];
}
// If user is 20 or more
if ($age >= 20) {
$result['20+'] = $result['20+'] + $user['activity_score'];
}
}
With :
var_dump($result);
I got this :
array (size=2)
'16-20' => int 5
'20+' => int 402
EDIT WITHOUT FOREACH :
// I create a function that return an array with the score of user by age
function get_score($user) {
$result = array();
$current_year = date('Y');
$age = $current_year - $user['dob'];
if ($age < 20 && $age >= 16) {
$result['16-20'] = $user['activity_score'];
}
if ($age >= 20) {
$result['20+'] = $user['activity_score'];
}
return $result;
}
// Then I create my $result array :
$result = array(
'16-20' => array_sum(array_column(array_map( "get_score", $users), '16-20')),
'20+' => array_sum(array_column(array_map( "get_score", $users), '20+'))
);
I don't use a lot array function to be honest so I'm sure we can do this a better way, but this one works here :)
I got the same result with var_dump($result');