Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading