¿Cuál es la mejor manera de generar una nube de etiquetas de una matriz usando H1 a H6 para el tamaño? -- php campo con arrays campo con tag-cloud camp Relacionados El problema

What's the best way to generate a tag cloud from an array using h1 through h6 for sizing?


76
vote

problema

Español

Tengo las siguientes matrices:

  $artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"); $count = array(5, 3, 9, 1, 1, 3);   

Quiero generar una nube de etiquetas que tendrá artistas con un número más alto en $count se incluyen en h6 Etiquetas y el más bajo cerrado h1 etiquetas.

Original en ingles

I have the following arrays:

$artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"); $count = array(5, 3, 9, 1, 1, 3); 

I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags.

</div
        

Lista de respuestas

40
 
vote
vote
La mejor respuesta
 

También querrá agregarle una función logarítmica. (Tomado de Tagadelic, My Drupal Module para crear nubes de etiquetas http://drupal.org/project/tagadelic ):

  db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');  $steps = 6; $tags = array(); $min = 1e9; $max = -1e9;  while ($tag = db_fetch_object($result)) {     $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it     $tag->count = log($tag->count);     $min = min($min, $tag->count);     $max = max($max, $tag->count);     $tags[$tag->tid] = $tag; } // Note: we need to ensure the range is slightly too large to make sure even // the largest element is rounded down. $range = max(.01, $max - $min) * 1.0001;  foreach ($tags as $key => $value) {     $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range); }   

luego en su vista o plantilla:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" }   
 

You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds http://drupal.org/project/tagadelic):

db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');  $steps = 6; $tags = array(); $min = 1e9; $max = -1e9;  while ($tag = db_fetch_object($result)) {     $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it     $tag->count = log($tag->count);     $min = min($min, $tag->count);     $max = max($max, $tag->count);     $tags[$tag->tid] = $tag; } // Note: we need to ensure the range is slightly too large to make sure even // the largest element is rounded down. $range = max(.01, $max - $min) * 1.0001;  foreach ($tags as $key => $value) {     $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range); } 

Then in your view or template:

foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 
</div
 
 
30
 
vote

de la parte superior de mi cabeza ...

  $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) {     $normalized = $count[$x] / $highest;     $heading = ceil($normalized * 6); // 6 heading types     echo "<h".$heading.">".$artist[$x]."</h".$heading.">"; }   
 

Off the top of my head...

$artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) {     $normalized = $count[$x] / $highest;     $heading = ceil($normalized * 6); // 6 heading types     echo "<h".$heading.">".$artist[$x]."</h".$heading.">"; } 
</div
 
 
24
 
vote

Tal vez esto sea un poco académico y fuera del tema, pero las etiquetas hX no son la mejor opción para una nube de etiquetas por razones de la estructura de documentos y todo ese tipo de cosas.

Tal vez span S o un ol Con los atributos de clase apropiados (más algunos CSS)?

 

Perhaps this is a little academic and off topic but hX tags are probably not the best choice for a tag cloud for reasons of document structure and all that sort of thing.

Maybe spans or an ol with appropriate class attributes (plus some CSS)?

</div
 
 
8
 
vote

Hemos utilizado este fragmento por un tiempo, el crédito es prism-perfect.net. No usa las etiquetas H aunque

  <div id="tags">     <div class="title">Popular Searches</div>     <?php         // Snippet taken from [prism-perfect.net]          include "/path/to/public_html/search/settings/database.php";         include "/path/to/public_html/search/settings/conf.php";          $query = "SELECT query AS tag, COUNT(*) AS quantity         FROM sphider_query_log         WHERE results > 0         GROUP BY query         ORDER BY query ASC         LIMIT 10";          $result = mysql_query($query) or die(mysql_error());          while ($row = mysql_fetch_array($result)) {              $tags[$row['tag']] = $row['quantity'];         }          // change these font sizes if you will         $max_size = 30; // max font size in %         $min_size = 11; // min font size in %          // get the largest and smallest array values         $max_qty = max(array_values($tags));         $min_qty = min(array_values($tags));          // find the range of values         $spread = $max_qty - $min_qty;         if (0 == $spread) { // we don't want to divide by zero             $spread = 1;         }          // determine the font-size increment         // this is the increase per tag quantity (times used)         $step = ($max_size - $min_size)/($spread);          // loop through our tag array         foreach ($tags as $key => $value) {              // calculate CSS font-size             // find the $value in excess of $min_qty             // multiply by the font-size increment ($size)             // and add the $min_size set above             $size = $min_size + (($value - $min_qty) * $step);             // uncomment if you want sizes in whole %:             // $size = ceil($size);              // you'll need to put the link destination in place of the /search/search.php...             // (assuming your tag links to some sort of details page)             echo '<a href="/search/search.php?query='.$key.'&search=1" style="font-size: '.$size.'px"';             // perhaps adjust this title attribute for the things that are tagged             echo ' title="'.$value.' things tagged with '.$key.'"';             echo '>'.$key.'</a> ';             // notice the space at the end of the link         }     ?> </div>   
 

Have used this snippet for a while, credit is prism-perfect.net. Doesn't use H tags though

<div id="tags">     <div class="title">Popular Searches</div>     <?php         // Snippet taken from [prism-perfect.net]          include "/path/to/public_html/search/settings/database.php";         include "/path/to/public_html/search/settings/conf.php";          $query = "SELECT query AS tag, COUNT(*) AS quantity         FROM sphider_query_log         WHERE results > 0         GROUP BY query         ORDER BY query ASC         LIMIT 10";          $result = mysql_query($query) or die(mysql_error());          while ($row = mysql_fetch_array($result)) {              $tags[$row['tag']] = $row['quantity'];         }          // change these font sizes if you will         $max_size = 30; // max font size in %         $min_size = 11; // min font size in %          // get the largest and smallest array values         $max_qty = max(array_values($tags));         $min_qty = min(array_values($tags));          // find the range of values         $spread = $max_qty - $min_qty;         if (0 == $spread) { // we don't want to divide by zero             $spread = 1;         }          // determine the font-size increment         // this is the increase per tag quantity (times used)         $step = ($max_size - $min_size)/($spread);          // loop through our tag array         foreach ($tags as $key => $value) {              // calculate CSS font-size             // find the $value in excess of $min_qty             // multiply by the font-size increment ($size)             // and add the $min_size set above             $size = $min_size + (($value - $min_qty) * $step);             // uncomment if you want sizes in whole %:             // $size = ceil($size);              // you'll need to put the link destination in place of the /search/search.php...             // (assuming your tag links to some sort of details page)             echo '<a href="/search/search.php?query='.$key.'&search=1" style="font-size: '.$size.'px"';             // perhaps adjust this title attribute for the things that are tagged             echo ' title="'.$value.' things tagged with '.$key.'"';             echo '>'.$key.'</a> ';             // notice the space at the end of the link         }     ?> </div> 
</div
 
 
 
 
6
 
vote

@ryan

Eso es correcto, pero en realidad hace las etiquetas con el menor número, más grande. Este código ha sido probado:

  $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for ($x = 0; $x < count($artist); $x++) {     $normalized =  ($highest - $count[$x]+1) / $highest;     $heading = ceil($normalized * 6); // 6 heading types     echo "<h$heading>{$artist[$x]}</h$heading>"; }   
 

@Ryan

That's correct but it actually makes the tags with the least number, larger. This code has been tested:

$artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for ($x = 0; $x < count($artist); $x++) {     $normalized =  ($highest - $count[$x]+1) / $highest;     $heading = ceil($normalized * 6); // 6 heading types     echo "<h$heading>{$artist[$x]}</h$heading>"; } 
</div
 
 
2
 
vote

Este método es para SQL/PostgreSQL fanáticos. Hace todo el trabajo en la base de datos, e imprime el texto con el enlace "Slugified". Utiliza la doctrina ORM Solo para la llamada SQL, no estoy usando objetos. Supongamos que tenemos 10 tamaños:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 0  

Luego, le imprime con alguna clase CSS, desde .Tagranking10 (lo mejor) a .Tagranking1 (lo peor):

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 111  

y este es el foreach ($tags as $tag) { $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 2 :

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 3  

Este método muestra todas las etiquetas. Si tiene muchos de ellos, probablemente no quiera que su nube de etiquetas se convierta en una tormenta de etiquetas . En ese caso, agregaría una cláusula <div id="tags"> <div class="title">Popular Searches</div> <?php // Snippet taken from [prism-perfect.net] include "/path/to/public_html/search/settings/database.php"; include "/path/to/public_html/search/settings/conf.php"; $query = "SELECT query AS tag, COUNT(*) AS quantity FROM sphider_query_log WHERE results > 0 GROUP BY query ORDER BY query ASC LIMIT 10"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)) { $tags[$row['tag']] = $row['quantity']; } // change these font sizes if you will $max_size = 30; // max font size in % $min_size = 11; // min font size in % // get the largest and smallest array values $max_qty = max(array_values($tags)); $min_qty = min(array_values($tags)); // find the range of values $spread = $max_qty - $min_qty; if (0 == $spread) { // we don't want to divide by zero $spread = 1; } // determine the font-size increment // this is the increase per tag quantity (times used) $step = ($max_size - $min_size)/($spread); // loop through our tag array foreach ($tags as $key => $value) { // calculate CSS font-size // find the $value in excess of $min_qty // multiply by the font-size increment ($size) // and add the $min_size set above $size = $min_size + (($value - $min_qty) * $step); // uncomment if you want sizes in whole %: // $size = ceil($size); // you'll need to put the link destination in place of the /search/search.php... // (assuming your tag links to some sort of details page) echo '<a href="/search/search.php?query='.$key.'&search=1" style="font-size: '.$size.'px"'; // perhaps adjust this title attribute for the things that are tagged echo ' title="'.$value.' things tagged with '.$key.'"'; echo '>'.$key.'</a> '; // notice the space at the end of the link } ?> </div> 14 a su consulta SQL:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 5  

Eso es todo

 

This method is for SQL/PostgreSQL fanatics. It does the entire job in the database, and it prints text with "slugified" link. It uses Doctrine ORM just for the sql call, I'm not using objects. Suppose we have 10 sizes:

public function getAllForTagCloud($fontSizes = 10) {     $sql = sprintf("SELECT count(tag) as tagcount,tag,slug,      floor((count(*) * %d )/(select max(t) from          (select count(tag) as t from magazine_tag group by tag) t)::numeric(6,2))           as ranking           from magazine_tag mt group by tag,slug", $fontSizes);      $q = Doctrine_Manager::getInstance()->getCurrentConnection();     return $q->execute($sql); } 

then you print them with some CSS class, from .tagranking10 (the best) to .tagranking1 (the worst):

<?php foreach ($allTags as $tag): ?>     <span class="<?php echo 'tagrank'.$tag['ranking'] ?>">         <?php echo sprintf('<a rel="tag" href="/search/by/tag/%s">%s</a>',              $tag['slug'], $tag['tag']         ); ?>     </span> <?php endforeach; ?> 

and this is the CSS:

/* put your size of choice */ .tagrank1{font-size: 0.3em;} .tagrank2{font-size: 0.4em;} .tagrank3{font-size: 0.5em;}  /* go on till tagrank10 */ 

This method displays all tags. If you have a lot of them, you probably don't want your tag cloud to become a tag storm. In that case you would append an HAVING TO clause to your SQL query:

-- minimum tag count is 8 --  HAVING count(tag) > 7 

That's all

</div
 
 
1
 
vote

como ayudante en rieles:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 6  

Llame a esto desde la vista:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 7  

Este elemento foreach ($tags as $tag) { $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 8 en una matriz que se convertirá en una cadena en la vista para renderizar en última instancia, así:

  foreach ($tags as $tag) {     $output .= "<h$tag->weight>$tag->name</h$tag->weight>" } 9  

Sería mejor tener un atributo <div id="tags"> <div class="title">Popular Searches</div> <?php // Snippet taken from [prism-perfect.net] include "/path/to/public_html/search/settings/database.php"; include "/path/to/public_html/search/settings/conf.php"; $query = "SELECT query AS tag, COUNT(*) AS quantity FROM sphider_query_log WHERE results > 0 GROUP BY query ORDER BY query ASC LIMIT 10"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)) { $tags[$row['tag']] = $row['quantity']; } // change these font sizes if you will $max_size = 30; // max font size in % $min_size = 11; // min font size in % // get the largest and smallest array values $max_qty = max(array_values($tags)); $min_qty = min(array_values($tags)); // find the range of values $spread = $max_qty - $min_qty; if (0 == $spread) { // we don't want to divide by zero $spread = 1; } // determine the font-size increment // this is the increase per tag quantity (times used) $step = ($max_size - $min_size)/($spread); // loop through our tag array foreach ($tags as $key => $value) { // calculate CSS font-size // find the $value in excess of $min_qty // multiply by the font-size increment ($size) // and add the $min_size set above $size = $min_size + (($value - $min_qty) * $step); // uncomment if you want sizes in whole %: // $size = ceil($size); // you'll need to put the link destination in place of the /search/search.php... // (assuming your tag links to some sort of details page) echo '<a href="/search/search.php?query='.$key.'&search=1" style="font-size: '.$size.'px"'; // perhaps adjust this title attribute for the things that are tagged echo ' title="'.$value.' things tagged with '.$key.'"'; echo '>'.$key.'</a> '; // notice the space at the end of the link } ?> </div> 20 y hacer referencia a las clases en una hoja de estilo como se menciona por Brendan arriba. Mucho mejor que el uso de $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) { $normalized = $count[$x] / $highest; $heading = ceil($normalized * 6); // 6 heading types echo "<h".$heading.">".$artist[$x]."</h".$heading.">"; } 1 semánticamente y hay un equipaje de menos estilo con un $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) { $normalized = $count[$x] / $highest; $heading = ceil($normalized * 6); // 6 heading types echo "<h".$heading.">".$artist[$x]."</h".$heading.">"; } 2 .

 

As a helper in Rails:

def tag_cloud (strings, counts)     max = counts.max     strings.map { |a| "<span style='font-size:#{((counts[strings.index(a)] * 4.0)/max).ceil}em'>#{a}</span> "  } end 

Call this from the view:

<%= tag_cloud($artists, $counts) %> 

This outputs <span style='font-size:_em'> elements in an array that will be converted to a string in the view to ultimately render like so:

<span style='font-size:3em'>the roots</span> <span style='font-size:2em'>michael jackson</span>  <span style='font-size:4em'>billy idol</span>  <span style='font-size:1em'>more</span>  <span style='font-size:1em'>and more</span>  <span style='font-size:2em'>and_YET_MORE</span>  

It would be better to have a class attribute and reference the classes in a style sheet as mentioned by Brendan above. Much better than using h1-h6 semantically and there's less style baggage with a <span>.

</div
 
 
 
 
0
 
vote

Sé que es un post muy antiguo, todavía estoy publicando mi opinión, ya que puede ayudar a alguien en el futuro.

Aquí está el TagCloud que utilizo en mi sitio web: http://www.vbausefulcodes.in/

  $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) {     $normalized = $count[$x] / $highest;     $heading = ceil($normalized * 6); // 6 heading types     echo "<h".$heading.">".$artist[$x]."</h".$heading.">"; } 3  
 

I know it's a very old post, still I'm posting my view as it may help someone in future.

Here is the tagcloud I used in my website: http://www.vbausefulcodes.in/

<?php $input= array("vba","macros","excel","outlook","powerpoint","access","database","interview questions","sendkeys","word","excel projects","visual basic projects","excel vba","macro","excel visual basic","tutorial","programming","learn macros","vba examples");  $rand_tags = array_rand($input, 5); for ($x = 0; $x <= 4; $x++) {     $size = rand ( 1 , 4 );     echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>"; }  echo "<br>"; $rand_tags = array_rand($input, 7); for ($x = 0; $x <= 6; $x++) {     $size = rand ( 1 , 4 );     echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>"; }  echo "<br>"; $rand_tags = array_rand($input, 5); for ($x = 0; $x <= 4; $x++) {     $size = rand ( 1 , 4 );     echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>"; } ?> 
</div
 
 

Relacionados problema

4  Tag Cloud Web Service?  ( Tag cloud web service ) 
¿Hay un servicio web público y gratuito que genera nubes de etiquetas? Estoy buscando algo como la tabla de Google: URL IN, IMAGE OUT. ...

3  JQUERY TAG-IT STYLING DE INPUT DEL COMPRIMIENTO  ( Jquery tag it plugins input field styling ) 
html DrawerLayout3 jquery DrawerLayout4 Quiero controlar el tamaño del campo de entrada, ¿cómo puedo hacer eso? ...

0  Etiquetas de filtro en Orchard CMS a solo blogs  ( Filter tags in orchard cms to only blogs ) 
En Orchard CMS, estoy tratando de encontrar una manera de filtrar las etiquetas en la nube de etiquetas para devolver las etiquetas solo desde las publicacion...

0  Problema de la cookie de AnyChart, atributo Samesite  ( Anychart cookie problem samesite attribute ) 
Añadido una tabla de TagCloud desde AnyChart en mi página de destino, pero encuentro esta advertencia y la tabla no es visible desde hace unos días. Esta es...

5  Cloud de etiquetas de esfera 3D [cerrado]  ( 3d sphere tag cloud ) 
cerrado. Esta pregunta no cumple con pautas de desbordamiento de pila . Actualmente no está aceptando respuestas. ...

7  Ayuda a entender el algoritmo para la nube de etiquetas  ( Help understand the algorithm for tag cloud ) 
Me gustaría entender el algoritmo / implementación de la nube de etiquetas. en Tag Cloud Obtenemos las siguientes etiquetas (peso) Etiqueta: la etiqueta ...

0  Nube de palabras en ASP.NET, filtrando palabras comunes  ( Word cloud in asp net filtering common words ) 
Quiero desarrollar una nube de palabras para un proyecto en el que estoy trabajando. Mi aplicación está conectada a una base de datos que tiene una serie de p...

76  ¿Cuál es la mejor manera de generar una nube de etiquetas de una matriz usando H1 a H6 para el tamaño?  ( Whats the best way to generate a tag cloud from an array using h1 through h6 fo ) 
Tengo las siguientes matrices: $artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"); $count = array(5, 3, 9, 1...

-1  Mostrar un montón de enlaces como nube  ( Display a bunch of links as cloud ) 
Mi cliente quiere que cree una página con un montón de enlaces externos que se muestran como una nube. Quiere tener la capacidad de agregar enlaces externos y...

202  Algoritmo para implementar una nube de palabras como Wordle  ( Algorithm to implement a word cloud like wordle ) 
Contexto Eche un vistazo a Wordle: http://www.wordle.net/ es mucho mejor que parece que cualquier otra palabra generadores de nube que he visto NOTA:...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos