簡體   English   中英

我在計數行並將其在php中排序時遇到問題

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

我有一個稱為“標簽”的表,該表將所有給定標簽逐行存儲到圖像中:

圖片

我想獲取有關“最受歡迎”標簽的數據,因此我嘗試對它們進行計數。 我設法成功列出並計數了標簽圖像,但無法按值對它們進行sort()排序。

我嘗試使用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;

將您的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