Search code examples
phparrayssumkeyword

Way to count a php array with key separation


I could need some help from the experts here :)

I do have an php array:

Array ( [A] => 5 [B] => 1 [A,B] => 5 )

For statistics i need to summ the value for each keyword. So I would need an output like this:

Array ( [A] => 10 [B] => 6 )

Someone an idea? Any help is much appreciated :)


Solution

  • $arr = [ 'A' => 5, 'B' => 1, 'A,B' => 5 ];
    
    $result = [];
    
    array_walk($arr, function ($value, $key) use (&$result) {
      $keys = explode(',', $key);
      foreach ($keys as $key) {
        if (array_key_exists($key, $result)) {
          $result[$key] += $value;
        } else {
          $result[$key] = $value;
        }
      }
    });
    
    print_r($result);
    

    Output:

    Array
    (
        [A] => 10
        [B] => 6
    )