简体   繁体   English

我在计数行并将其在php中排序时遇到问题

[英]I have a problem with counting rows and sorting them in php

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. 我设法成功列出并计数了标签图像,但无法按值对它们进行sort()排序。

I have tried using ar/sort(), creating a third loop.... 我尝试使用ar / sort()创建第三个循环。

<?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 将您的count_tags_sql函数和$ tagname循环更改为以下

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM