Jump to content

PHP & MySQL Tag Cloud (Kind of)


chordsoflife

Recommended Posts

Let's say I have a database full of names. for the first_name field, I have jane, josh, jacob, and jill. What I'm looking to do is output those names all at lets say a font size of 10px. Now, lets say I add another few names to the database... jane, jane, and josh.

 

Now I've got three janes, two josh's and one of everything else.

 

So now I'd like to output jane only once on the page but in a font size of 12px, josh as 11px, and everything else at 10 still.

 

Can anyone help me out with that?

Link to comment
https://forums.phpfreaks.com/topic/126802-php-mysql-tag-cloud-kind-of/
Share on other sites

here's an example of how you could do it.

 

<?php
$testNames = array('jane', 'josh', 'jacob', 'jill', 'jane', 'josh', 'jane');

$sizes = array();
foreach($testNames as $name) {
$sizes[$name] = (isset($sizes[$name])) ? ++$sizes[$name] : 10;
}

foreach($sizes as $name => $size) {
echo "<span style='font-size:{$size}px'>{$name}</span>";
}
?>

Ok, that's very helpful. Just a few questions... I want to understand it, not just get it to work.

 

I'll be able to store the information from the database as an array, but what exactly does "$testNames as $name" mean? Or rather, what are you telling PHP there?

 

Also, what is that question mark before ++$sizes?

 

Thanks!

the foreach loop is an easy way of looping through arrays.

http://us3.php.net/foreach

 

the = ? : is a ternary operator

http://us2.php.net/operators.comparison#language.operators.comparison.ternary

 

it's just a shortcut for if/then/else.. you could replace that one line with

 

if(isset($sizes[$name])) {
   ++$sizes[$name];
}
else {
   $sizes[$name] = 10;
}

 

the way I wrote it is actually a bit messy, though it will work the ++ is a little confusing as that increments the value and then re-sets it. A more readable way to have written the line would be

 

$sizes[$name] = (isset($sizes[$name])) ? $sizes[$name]+1 : 10;

Ok, that's very helpful. Just a few questions... I want to understand it, not just get it to work.

 

I'll be able to store the information from the database as an array, but what exactly does "$testNames as $name" mean? Or rather, what are you telling PHP there?

 

Also, what is that question mark before ++$sizes?

 

Thanks!

 

"$testNames as $name" means that for every item in $testNames, you'll find the current value (based on the loop) in $name.

<?php
$arr = array('testing', 'test again', 'some more', 'ever more!');
foreach ($arr as $element) {
   echo "$element <br />";
}

 

Also, the (bool) ? true_cond : false_cond structure is called the ternary operator.  Google it or look in the manual.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.