Search code examples
phparraysuniqueword-countarray-column

Get count of each unique word across all strings in an array column


I'd like to get a unique word count including all strings in an array column.

Input:

[
    [
        "Query" => "hehe haha hihi",
        "Merry" => "1.11"
    ],
    [
         "Query" => "hehe hoho hrooo",
         "Merry" => "1.12"
    ]
]

I want to get the values of the "Query" key of EACH array (not just first which I'm getting) and explode it by space " " so that I can match the Query value that repeats.

Desired result:

[
    'hehe' => 2,
    'haha' => 1,
    'hihi' => 1,
    'hrooo' => 1
]

So what I want to achieve is to compare the "Query" key in each nested array so that I can find those that match and then count them with array_count_values() to achieve the above result.

But when I loop the array I only get the first nested array result, like this:

[
    'hehe' => 1,
    'haha' => 1,
    'hihi' => 1
]

and not from all nested arrays.

Let's say that the array is in variable $data, and what I did so far is:

foreach($data as $k => $v)
{
    // now the $k is 0, and $v is the whole first object 
    // (with both Query and Merry keys, if I foreach again
  foreach($v as $key => $value)
  {
      // now the $key is Query, and $value is "hehe haha hihi" which is great! 
      // But I want the same result for ALL nested arrays, not just this first. 
  }
}

How to achive that and where am I losing it?


Solution

  • You can map the sentence to an array of words, merge them all and then count:

    $wordArrays = array_map(function ($v) { return explode(" ", $v["Query"]; }, $array); //Get the words from the sentence
    $combinedWordArray = call_user_func_array('array_merge', $wordArrays); //Flatten the array
    $result = array_count_values($combinedWordArray); //Count
    

    Example: http://sandbox.onlinephpfunctions.com/code/8f234715df744fe93d8cf5238f90e37fb65ca7c4