I have a table called "tags" which stores all given tags to an image row by row:
I want to get data about the "most popular" tags, so I tried counting them. I manage to successfully list and count the tags image but I can not manage to sort() them by value.
I have tried using ar/sort(), creating a third loop....
<?php
function count_tags_sql($tag) {
global $db;
// count
$sql = $db->query("SELECT tags FROM tags WHERE tags = '$tag'");
$sql->execute();
echo $tag.'('.$sql->rowcount().')<br>';
}
// get tags
$sql = $db ->prepare("SELECT * FROM tags");
$sql->execute();
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$tagname[] = $row['tags'];
}
// remove duplicates
$tagname = array_unique($tagname);
// output tags
foreach($tagname as $tag) {
echo count_tags_sql($tag);
}
?>
您想使用计数,最好是这样:
SELECT tags,count(*) as usages FROM tags GROUP BY 1 ORDER BY 2 DESC;
change your count_tags_sql function and $tagname for loop to below
function count_tags_sql($tag) {
global $db;
// count
$sql = $db->query("SELECT tags FROM tags WHERE tags = '$tag'");
$sql->execute();
return $sql->rowcount()
}
// output tags
$tag_arr = [];
foreach($tagname as $tag) {
$tag_arr[$tag] = count_tags_sql($tag);
}
// Sorted array
asort($tag_arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.