1

I want to find tags from the last 50 posts and print them with the number of how many the tag was repeated?

so far I printed the tags. how can I print the number of "how many the tag was repeated".

$posts = mysql_query("SELECT * FROM posts ORDER BY id desc Limit 50");

while($fetch_tags = mysql_fetch_assoc($posts))
{
    $tags_array  = str_word_count($fetch_tags['tags'],1);
}

foreach($tags_array as $tag)
{
    echo $tag .'<br/>';   // ex: html</br/>php</br/> ...etc.
}

i want the output be like $tag:$number<br/>...

Abdullah Salma
  • 560
  • 7
  • 20
  • Yep this is a duplicate. Check this answer: http://stackoverflow.com/a/2984800/171318 – hek2mgl Jun 04 '13 at 00:18
  • @showdev the problem here it's in while no normal $string otherwise your link would work.. – Abdullah Salma Jun 04 '13 at 00:19
  • @hek2mgl did you try it ? it's work if it's a normal string. but in while it does not – Abdullah Salma Jun 04 '13 at 00:20
  • 1
    It works anywhere. In your case: `array_count_values(str_word_count($fetch_tags['tags'], 1))`. You'll need to revise your output loop as the new array is structured differently. – showdev Jun 04 '13 at 00:21
  • @AbdullahSalma I'm with showdev. However just wanted to help (as the answer I've linked is great) – hek2mgl Jun 04 '13 at 00:22

1 Answers1

0

You can read the array like:

$posts = mysql_query("SELECT * FROM posts ORDER BY id desc Limit 50");
$results = array();

while($fetch_tags = mysql_fetch_assoc($posts))
{
    $tags_array  = str_word_count($fetch_tags['tags'],1);

    foreach($tags_array AS $index => $tag) {
        if ( !isset($results[$tag]) ) $results[$tag] = 1; // First occurrence
        else $results[$tag] += 1; // Add one occurrence
    }
}

// Now that we counted, print the results
foreach($results AS $tag => $number)
{
    echo "{$tag} : {$number}<br />\n";
}
Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30
  • ammm how do i test your code ? with the information I got from db ? do I put the first foreach inside the while ? i test it i shows 1 : 3 ..? i have 2 posts one with "php javascript css" and the other "php javascript"... could explain more.. – Abdullah Salma Jun 04 '13 at 00:33
  • Try it inside your while, just below $tags_array = str_word_count($fetch_tags['tags'],1); – Alejandro Iván Jun 04 '13 at 00:37
  • i tried it shows 1 for each word... I changed the first post's tag into `php javascript css php`. now the php tags printed like {php}:{2}. **BUT** there should be three because the second post's tags are `php javascript`. look like if there is repeated tags in the same post it appear but in different post it doesn't, and it needs to be the opposite. I hope I explained my point ? can you help ? – Abdullah Salma Jun 04 '13 at 00:45
  • I modified the answer, try it now. – Alejandro Iván Jun 04 '13 at 00:50
  • you're my hero... thanks alot ... :)~ – Abdullah Salma Jun 04 '13 at 00:51