PHP和MySQL:计算和排序数组中最常用的值然后打印

I am wanting to order my array by how many times a value comes up in that array and also then print only the highest 6 results.

This is what I have at the moment:

        $delimiter = " ";
        $tags = array();

        $sql = mysql_query("SELECT tags FROM share WHERE site_id = $id");

        while($result = mysql_fetch_assoc($sql)) {
            $tags_new = explode($delimiter, $result['tags']);
            $tags = array_merge($tags , $tags_new);
        }

Hum... You can do that:

    while($result = mysql_fetch_assoc($sql)) {
        $tags_new = explode($delimiter, $result['tags']);
        foreach($tags_new as $tag){
            $tags[$tag]++;
        }
    }

After, you need to sort by value, using function sort or rsort (desc).

    rsort($tags);

Last, you need slice and get only 6 first:

    $high_tags = array_slice($tags, 0, 6, true);

Edit: showing key and value:

    foreach($high_tags as $key => $value){
        echo "{$key}: {$value}";
    }

Or just do:

    $high_keys = array_keys($high_tags);

    var_dump($high_keys);

Bye :)

You can do this in MySQL with the following query:

SELECT tags, COUNT(tags) AS tag_count
FROM share WHERE site_id = $id
GROUP BY tags
ORDER BY tag_count DESC
LIMIT 6;

This will select the top 6 tags with the highest count. You can then loop over them similar to the PHP code you already have.