0

I have an array like this

 Array ( 
        [0] => Array ( [id_doc] => 1 [term] => curi ) 
        [1] => Array ( [id_doc] => 1 [term] => tidur ) 
        [2] => Array ( [id_doc] => 1 [term] => kamar ) 
        [3] => Array ( [id_doc] => 2 [term] => curi ) 
        [4] => Array ( [id_doc] => 2 [term] => cela ) 
        [5] => Array ( [id_doc] => 2 [term] => hukum ) 
        [6] => Array ( [id_doc] => 3 [term] => nyanyi ) 
        [7] => Array ( [id_doc] => 3 [term] => dangdut ) 
        [8] => Array ( [id_doc] => 3 [term] => curi )   
    ) 

How to get count of document frequency from term that on these document. I want the output like this.

Array ( 
        [0] => Array ( [id_doc] => 1 [term] => curi [doc_frequency] => 3 ) 
        [1] => Array ( [id_doc] => 1 [term] => tidur [doc_frequency] => 1 ) 
        [2] => Array ( [id_doc] => 1 [term] => kamar [doc_frequency] => 1 ) 
        [3] => Array ( [id_doc] => 2 [term] => curi [doc_frequency] => 3 ) 
        [4] => Array ( [id_doc] => 2 [term] => cela [doc_frequency] => 1 ) 
        [5] => Array ( [id_doc] => 2 [term] => hukum [doc_frequency] => 1 ) 
        [6] => Array ( [id_doc] => 3 [term] => nyanyi [doc_frequency] => 1 ) 
        [7] => Array ( [id_doc] => 3 [term] => dangdut [doc_frequency] => 1 ) 
        [8] => Array ( [id_doc] => 3 [term] => curi [doc_frequency] => 3 )  
    ) 

So term 'curi' have 3 document frequency, because its appear on 3 documents. I have tried with this

$count_df = array_count_values(array_map(function($item) {
   return $item['term'];
}, $dokumen_frek));
print_r($count_df);

but the result is

Array ( 
[curi] => 3 
[tidur] => 1 
[kamar] => 1 
[cela] => 1 
[hukum] => 1 
[nyanyi] => 1 
[dangdut] => 1 

)

Bangjeko
  • 17
  • 4
  • 2
    StackOverflow expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592), and we also [don't answer homework questions](https://softwareengineering.meta.stackexchange.com/questions/6166). Please update your question to show what you have already tried in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). For further information, please see [how to ask good questions](http://stackoverflow.com/help/how-to-ask), and take the [tour of the site](http://stackoverflow.com/tour) :) – Barmar Dec 07 '17 at 19:58
  • Use an associative array whose keys are the document names and values are the frequencies. Loop through your array, and increment the frequency of the element with the current name. Then when you're done you can add the frequencies to the original array. – Barmar Dec 07 '17 at 19:59
  • Check this https://stackoverflow.com/questions/32603607/php-array-count-values-with-multidimensional-array – Ravinder Reddy Dec 07 '17 at 20:12

1 Answers1

1

Use array_count_values function

$terms = array_count_values(array_column($arr, 'term'));

foreach($arr as &$x) {
   $x['doc_frequency'] = $terms[$x['term']];
}

demo

splash58
  • 26,043
  • 3
  • 22
  • 34