Search code examples
phparrayssumgroupingassociative-array

Group and sum 2d array data into a flat associative array


I am trying to parse an array of strings with irrelevant leading text (to be removed) then create an associative array where values are summed if the same key is encountered more than once.

$assessmentArr = [
    'a_b_money-rewards=30',
    'c_d_status-stability=15',
    'e_f_personal-professional-development=32',
    'g_h_community-support=9',
    'i_j_money-rewards=12',
    'k_l_status-stability=16',
    'm_n_personal-professional-development=29',
];

foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);
    $resultArr = explode("=", $fullArr[2]);
    // what do I do with $resultArr?
}

Desired result:

Array
(
    [community-support] => 33
    [money-rewards] => 42
    [status-stability] => 31
    [personal-professional-development] => 61
)

I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?


Solution

  • Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.

    (Add this code in your loop):

    if(!isset($result[$resultArr[0]]))
        $result[$resultArr[0]] = $resultArr[1];
    else
        $result[$resultArr[0]] += $resultArr[1];
    

    Then you have your desired array:

    print_r($result);