phparraysmultidimensional-arraysumgrouping

Group 2d data by a column and and each group sum one column and count occurrences


I've got this multidimensional array:

$sales = Array (
[0] => Array (
    [salesID] => 1
    [price] => 50
    [user_first] => Jane
    [user_last] => Doe
)
[1] => Array (
    [salesID] => 2
    [price] => 250
    [user_first] => John
    [user_last] => Smith
)
[2] => Array (
    [salesID] => 1
    [price] => 50
    [user_first] => Jane
    [user_last] => Doe
)
);

That I need to turn into:

$sales = Array(
[2] => Array (
    [Name] => John Smith
    [Sales] => 250
    [Signups] => 1
)
[1] => Array (
    [Name] => Jane Doe
    [Sales] => 100
    [Signups] => 2
)
);

I've currently got the following that will create the new array, but it doesn't update the values in the new array.

$leader_board = array();
foreach ($sales as $index => $row) {
    if (!in_array($row['salesID'], $leader_board)) {
        $new_row = array('Name' => $row['user_first'] . ' ' . $row['user_last'], 'SignUps' => 1, 'Sales' => $row['price']);
        $leader_board[$row['salesID']] = $new_row;
    } else {
        $leader_board[$row['salesID']]['SignUps'] += 1;
        $leader_board[$row['salesID']]['Sales'] += $row['price'];
    }
}

Solution

  • You can do it like below (I have given answer based on your input and expected output only, not based on your code what you tried):-

    $final_array = array();
    
    foreach ($sales as $sale) {
      $final_array[$sale['id']]['Name'] = $sale['user_first']." ".$sale['user_last'];
      $final_array[$sale['id']]['Sales'] = (isset($final_array[$sale['id']]['Sales'])) ? $final_array[$sale['id']]['Sales'] + $sale['price'] : $sale['price'];
      $final_array[$sale['id']]['Signups'] = (isset($final_array[$sale['id']]['Signups'])) ? $final_array[$sale['id']]['Signups'] + 1 : 1;
    }
    krsort($final_array);// Sort array by key in reverse order
    print_r($final_array);
    

    Reference:- krsort()