0

So I am searching a large body of text and extracting common phrases, then I end up with an array like this:

Array(
    [past due] => 21
    [past due notice] => 7
    [past due 60 day] => 17
    [60 day notice] => 32
)

The keys are the phrases and the values are the number of times that phrase appeared in the given text. In the example above, I would like to combine these keys and sum the values because they all mean the same thing, to me. So I would end up with an array like this:

Array(
    [past due] => 77
)

This is just an example, the keys, values, etc. will constantly be changing. I am just starting on this piece of the project so there is no code to post yet. I am just looking for ideas, direction, etc. so I don't have to reinvent the wheel if someone has done something similar or as an idea. As always, thanks in advance!

UPDATE:

With all of the contributions here and in reading other questions, I think I am going to try to group them using regex before I build the array.

Community
  • 1
  • 1
Drewness
  • 5,004
  • 4
  • 32
  • 50
  • This question does not show any research effort. It is important to **do your homework**. Tell us what you found and ***why*** it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. [FAQ](http://stackoverflow.com/questions/how-to-ask). – Kermit Mar 29 '13 at 16:44
  • You will need to create an array map. – Kermit Mar 29 '13 at 16:44
  • @PolishPrince - Noted. Sounds like I posted this to soon. Thanks for the input on using array_map(). – Drewness Mar 29 '13 at 16:49
  • possible duplicate of [How to sum values of the array of the same key](http://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key) – Michael Mar 29 '13 at 16:57
  • @MichaelRushton - It is very similar. The main difference being my array keys are not identical, as they are in that question. It is however good reference so thank you! – Drewness Mar 29 '13 at 17:05
  • Ah, sorry. Misunderstood. – Michael Mar 29 '13 at 17:11

2 Answers2

0

I think there is very similar questions, where you can find your answer.

Check this:

Merging arrays with the same keys

PHP - Merge duplicate array keys in a multidimensional array

Community
  • 1
  • 1
mirsad
  • 182
  • 12
0

You can use array_sum:

$result = array('past_date' => array_sum($array));

Of course, this requires that you build the array first, grouping by a common meaning. PHP doesn't understand the semantics of language, obviously.

Michael
  • 11,912
  • 6
  • 49
  • 64