Hello I am working on a site that uses expedias api. Basically I get a number of people per room, and I want to echo out a little man image for each person. So if I have occupancy of 5 for example and I need to echo 5 tags with the little man as a src. Any idea how to do this??
Well let's say you have the amount of people stored in a variable.
$occupancy = 5;
You can then plug in that number into a for loop, and have the program cycle through that many times.
for($n = 0; $n < $occupancy; $n++) {
// Disco
}
You can read more about control structures here.
You should be interested in str_repeat().
Something like this should work:
$img_multi = str_repeat('<img src="man.png" alt="man"/>', $repeat);
echo $img_multi;
Revisiting this answer, a much more efficient solution:
Assuming the image is 12px wide by 16px high - adjust for your needs.
$width = 12 * $repeat;
$height = 16;
echo '<span style="'
.'display: inline-block;'
.'width: '.$width.'px;'
.'height: '.$height.'px;'
.'background-image: url(man.png);'
.'"></span>';
This will produce a single element of the appropriate size to show $repeat copies of the image, side-by-side.
First result googling "php loops"
Might be worth trying.
Related
Quick background on myself. This is my first time coding in PHP. I have a computer information systems degree, learned C++, VB, Cobol and Java in college (about 15 years ago), but have not really used it since. Some stuff is coming back to me as I learn this.
I'm attempting to simulate the opening of randomized packs of cards for a trading card game. The end result would be printing out 4 pages. Each page will list 12 card numbers, and all of the information on the card.
Here's what I was planning on doing:
Step One:
Generate 180 random numbers from different ranges. Each number represents a card in the game.
range 1 = 35-74 (116 numbers)
range 2 = 75-106 (46 numbers)
range 3 = 107-134 (16 numbers, no duplicates)
range 4 = 135-142 (2 numbers, no duplicates)
Step Two:
Take the 180 numbers and break them down into 90 pairs.
Step Three:
From the 90 pairs, break them down to 4 sets of 6 pairs.
Step Four:
From the 4 sets of 6 pairs, list the card information for each number and make 4 printable pages, 1 for each set.
I've gotten as far as creating the 180 random numbers. I'm still working on getting the unique numbers. I've tried creating arrays for the numbers I need, but none of them work. Here's the last working code I have, which will generate the 180 numbers I need, however, range 3 and 4 need to be fixed to not allow duplicates.
The way i currently have this coded, it just displays the numbers on the screen. Should I be storing them in an array? Am I just completely tackling the wrong way?
<?php
// generate 116 common cards
echo "Commons: " . '<br />';
for ($commonfeed = 0; $commonfeed < 116; $commonfeed++) {
echo mt_rand(35, 74). '<br />';
}
// generate 46 uncommon cards
echo "Uncommons: " . '<br />';
for ($uncommonfeed = 0; $uncommonfeed < 46; $uncommonfeed++) {
echo mt_rand(75, 106). '<br />';
}
// generate 16 rare cards
echo "Rares: " . '<br />';
for ($rarefeed = 0; $rarefeed < 16; $rarefeed++) {
echo mt_rand(107, 134). '<br />';
}
// generate 2 super rare cards
echo "Super Rares: " . '<br />';
for ($superrarefeed = 0; $superrarefeed < 2; $superrarefeed++) {
echo mt_rand(135, 142). '<br />';
}
?>
Here's a solution you might try:
$cards = array();
// get cards per range
for($i = 0; $i < 116; $i++) {
// range 1:
$cards[] = mt_rand(35, 74);
// for the fun, let's also do range 2:
if($i < 46) {
$cards[] = mt_rand(75, 106);
}
}
// range 3: (and range 4)
$rare = array();
$superrare = array();
for ($i = 107; $i <= 134; $i++) {
$rare[] = $i;
// range 4:
if ($i <= 114) {
$superrare[] = $i + 28;
}
}
shuffle($rare);
shuffle($superrare); // not the best choice of randomness (check: http://stackoverflow.com/questions/5694319/how-random-is-phps-shuffle-function)
$cards = array_merge($cards, array_slice($rare, 0, 16));
$cards = array_merge($cards, array_slice($superrare, 0, 2));
// shuffle everything one more time since cards have been added randomly
// to the deck
shuffle($cards);
// now when we have everything in $cards - 180 of random cards, we can
// pack them
$pack1 = array_slice($cards, 0, 90);
$pack2 = array_slice($cards, 90, 90);
// always picking first n cards because they are all shuffled
$player1Drafted = array_slice($pack1, 0, 48);
$player2Drafted = array_slice($pack2, 0, 48);
// print it all
print_r(array('Player1' => $player1Drafted,
'Player2' => $player2Drafted));
In the end, I'm not entirely sure i guessed the drafting process OK, but it seemed to me that randomization was the biggest issue and that I solved it OK. Again, if you think that shuffle is not good enough, it can be done differently, but that's another story ;)
Since you are learning to code (again), I will answer using a few pointers instead of just generating some working code.
To start off with the last question: yes, i would be storing everything in an array. This way you can split "processing" code from "output" code.
Are you tackling this the wrong way? Hard to say, depends on all game mechanics and such. But to start easy: yes, it is a good start.
Using array_unique you can make an array unique, which you can use while generating the rare and superrare cards.
Onto the game mechanics: Are you sure you always want to give someone 16 rare cards and 2 super rare cards? What you could do, is create the total "deck of cards" up front, and then select the number of cards you would like:
$number_of_cards = 5;
$deck = [1,1,1,1,2,2,2,2,3,3,4,4,100,101,102];
shuffle($deck); // shuffle the cards
$selected = array_slice($deck, 0, $number_of_cards); // select the amount of cards
You can even just use this using strings instead of integers.
I have built a simple modular scale calculator, where I can enter a base number (say font size or line height) and an important number (maybe column width, page width, or another font size) and select a ratio (golden ratio for example) and the calculator will display a double stranded scale for use in page layout. see example below
I have been toying with the idea of allowing users to input points and picas and then displaying the scale in one or the other.
The problem is that picas are base 12 numbers (12 points to a pica), I figured if I could just convert the input (something like 16p6) to base 12 I could do the calculation and go from there.
I just can't work out how to do basic calculations in another base. I'm really just messing around to see what I can come up with, let me know if you think I'm barking up the wrong tree.
So my question is this how do I do calculations in base 12?
<?php
// basic modular scale calculation
$goldenRatio = 1.618;
$baseNumber = 16;
$i = 0;
while ($i <= 10) {
echo round($baseNumber,1). "<br>";
$baseNumber = $baseNumber * $goldenRatio;
$i++;
}
echo "<hr><br>";
// Attempt at base 12 calculation
$a=base_convert(16,10,12);
$b=base_convert(12,10,12);
$r = ($a*$b);
echo $a."*".$b."=";
echo $r;
I'm really just messing around to se what I can come up with, let me know if you think I'm barking up the wrong tree.
Update
To solve the problem of converting Picas to base points from a string like '12p6' I ended up using regex to first test if Picas and Points had been supplied the split the Picas and Points.
function isPica($data) {
if (preg_match('/^[0-9]+(?i)p([0-1]?[0-9])?$/i',$data)) {
return true;
}
return false;
}
function makePoints($data) {
$data = preg_replace('/^([0-9]+)((?i)p)(([0-1]?[0-9])?)$/i','$1.$3',$data);
$data = explode('.',$data);
$points = floor($data[0] * 12);
$points = $data[1] + $points;
return $points;
}
Modular Scale Calculator
Git Hub — Modular Scale Calculator
base_convert just converts the string representation. You can't do calculations using strings of numbers in base 12 in php. When dealing with imperial units, you usually have multiple "bases" to deal with. So it has to be done manually. When you're doing calculations, the base doesn't matter.
Convert all the different units to the smallest one (points). $a = 3*12 + 7;//3picas, 7points.
Do the calculations.
Convert back to original units.
$points = (int)$val % 12;
$picas = (int)($val / 12);
or
$picas = floor($val / 12);
$points = $val - 12*$picas;
I'm generating a 6 digit code from the following characters. These will be used to stamp on stickers.
They will be generated in batches of 10k or less (before printing) and I don't envisage there will ever be more than 1-2 million total (probably much less).
After I generate the batches of codes, I'll check the MySQL database of existing codes to ensure there are no duplicates.
// exclude problem chars: B8G6I1l0OQDS5Z2
$characters = 'ACEFHJKMNPRTUVWXY4937';
$string = '';
for ($i = 0; $i < 6; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
Is this a solid approach to generating the code?
How many possible permutations would there be? (6 Digit code from pool of 21 characters). Sorry math isn't my strong point
21^6 = 85766121 possibilities.
Using a DB and storing used values is bad. If you want to fake randomness you can use the following:
Reduce to 19 possible numbers and make use of the fact that groups of order p^k where p is an odd prime are always cyclic.
Take the group of order 7^19, using a generator co-prime to 7^19 (I'll pick 13^11, you can choose anything not divisible by 7).
Then the following works:
$previous = 0;
function generator($previous)
{
$generator = pow(13,11);
$modulus = pow(7,19); //int might be too small
$possibleChars = "ACEFHJKMNPRTUVWXY49";
$previous = ($previous + $generator) % $modulus;
$output='';
$temp = $previous;
for($i = 0; $i < 6; $i++) {
$output += $possibleChars[$temp % 19];
$temp = $temp / 19;
}
return $output;
}
It will cycle through all possible values and look a little random unless they go digging. An even safer alternative would be multiplicative groups but I forget my math already :(
There is a lot of possible combination with or without repetition so your logic would be sufficient
Collision would be frequent because you are using rand see str_shuffle and randomness.
Change rand to mt_rand
Use fast storage like memcached or redis not MySQL when checking
Total Possibility
21 ^ 6 = 85,766,121
85,766,121 should be ok , To add database to this generation try:
Example
$prifix = "stamp.";
$cache = new Memcache();
$cache->addserver("127.0.0.1");
$stamp = myRand(6);
while($cache->get($prifix . $stamp)) {
$stamp = myRand(6);
}
echo $stamp;
Function Used
function myRand($no, $str = "", $chr = 'ACEFHJKMNPRTUVWXY4937') {
$length = strlen($chr);
while($no --) {
$str .= $chr{mt_rand(0, $length- 1)};
}
return $str;
}
as Baba said generating a string on the fly will result in tons of collisions. the closer you will go to 80 millions already generated ones the harder it will became to get an available string
another solution could be to generate all possible combinations once, and store each of them in the database already, with some boolean column field that marks if a row/token is already used or not
then to get one of them
SELECT * FROM tokens WHERE tokenIsUsed = 0 ORDER BY RAND() LIMIT 0,1
and then mark it as already used
UPDATE tokens SET tokenIsUsed = 1 WHERE token = ...
You would have 21 ^ 6 codes = 85 766 121 ~ 85.8 million codes!
To generate them all (which would take some time), look at the selected answer to this question: algorithm that will take numbers or words and find all possible combinations.
I had the same problem, and I found very impressive open source solution:
http://www.hashids.org/php/
You can take and use it, also it's worth it to look in it's source code to understand what's happening under the hood.
Or... you can encode username+datetime in md5 and save to database, this for sure will generate an unique code ;)
Forgive me if this isn't a programming oriented question.
Lets say we have two sentences
[1]=This is a test idea
[2]=This is an experimental idea
If I jumble up [1]
[1]= a This idea test is
Would this count as plagiarism? What sort of logic do I have to apply to detect plagiarism.
I'm not making a complexed plagiarism service, but a rather simple one what can catch obvious plagiarism.
My logic is somewhat like this
<?php
$str1= "This is a test idea.";
$str2= "This is an experimental idea.";
echo "$str1<br>$str2<br>";
$str1Array = explode(" ",$str1);
$str2Array = explode(" ",$str2);
if(count($str1Array) > count($str2Array))
$max=count($str1Array);
else
$max=count($str2Array);
$word_seq = array();
$word_seq_history = array();
$c=0;
$plag_count=0;
for ($i = 0; $i < $max; $i++) {
$lev = levenshtein($str1Array[$i], $str2Array[$i]); // check for an exact match
if ($lev == 0) {
$c+=1;// (exact match)
//echo "<br>$c";
$word = $str1Array[$i];
array_push($word_seq,$word);
}
else
{
if($lev != 0){
if($c>=2)
$plag_count+= count($word_seq);
$current_seq = implode(" ", $word_seq);
array_push($word_seq_history,$current_seq);
echo $current_seq;
$c=0;
$word_seq= array();
}
}
}
echo "plag_count:";
echo $plag_count;
echo "max:";
echo $max;
echo "<br>" ;
echo ($plag_count/$max)*100;
?>
Output:
String 1: "This is a test idea."
String 2: "This is an experimental idea."
Words_Same:2 max:5
Plagiarism: 40%
Do I need to change it or is it fine the way it is?
What I would do to detect plagiarism in a very basic way is to first calibrate my system: ie first do a lot of comparisons with files from which you're sure aren't plagiated
1) compare a bunch of files with each other, detect the plagiarism rate with your function. Get out the words that are the most comonly used (let's say drop your rate up to XX%, trial and error here), put this words in your database and give them a weight of 0. Do this again without this words up to (less than XX%) (with regular expressions you can filter this words) and give them a weight of 1. And so on... Until you reach a plagiarism rate of nearly zero.
2) calculate the 'new' percent by sum(weight of words in your db that appear in the text)/ (the total weight of all your words) (and give the words that do not already come up in your database a weight of 10) = your rate
3) test it with plagiated stuff, if not ok, change a few parameters (weights)
I think this method, if used to check longer passages, will show a high level of correlation just because of common words, especially articles, prepositions, "be" verbs, and other common/overused words. If you're writing about a variety of subjects, be it code or Shakespeare, you're likely to run across a jargon sets that are common to many genuinely unique papers. I think you may need to look at an alternate approach. Have you done any research into plagiarism and its detection?
I want to display a color between red, yellow, green depending on a number between 1 to 100.
1 being green and 100 being red, 50 being yellow. I want to basically create a gradient between that.
So far, I tried:
$r = floor(255 * ($number / 100));
$g = 255 - $r;
And it somewhat does it, but gives me brownish & dark colors, & no yellow at all.
It's because you shouldn't change both channels at once but rise R in the first half and lower G in the second.
Try a function like this:
function GreenYellowRed($number) {
$number--; // working with 0-99 will be easier
if ($number < 50) {
// green to yellow
$r = floor(255 * ($number / 50));
$g = 255;
} else {
// yellow to red
$r = 255;
$g = floor(255 * ((50-$number%50) / 50));
}
$b = 0;
return "$r,$g,$b";
}
To test it:
$output = "";
for ($i = 1; $i <= 100; $i++) {
$rgb = GreenYellowRed($i);
$output .= "<div style='background-color: rgb($rgb)'>$rgb</div>";
}
echo $output;
I've found that dealing with the HSV color model is easier than the RGB model. It helps you easily choose the color you want to work with; with RGB you'd need to understand how different values of R, G and B will combine to give you the color you want/don't want.
Also, this SO question might be useful: How can I cycle through hex color codes in PHP?
I don't know of a mathematical model for a "color curve" that passes through specified RGB color values (e.g. what you describe as green/yellow/red), which would allow you to calculate any intermediate color in that curve. In any case, a model of a function (which is what that would be) is only as good as the data points it needs to fit, so you 'd have to be much more specific than green/yellow/red to get decent results even if someone points out the math.
Remember that we are not interested in mathematical interpolation here, but rather in "color-space interpolation" (a term which I just made up) -- in other words, what would look like a "natural" interpolation to a human.
An easier solution for those of us who do not have the necessary color theory knowledge, and which I 'd suggest, is to pre-select a number of colors with a color picker tool, divide the 0-100 range into as many bands as the colors you picked, and use simple integer division to project from 0-100 to a color band.
Food for thought: Indeed, how does SO decide the color of the upvote count for comments?
Update: I just asked the above over on meta. Let's see...
After a bit of looking, none of the solutions looked pleasing. As stated above, HSV is probably the way to go, since modern browsers can render color with it just fine.
To get a good idea of the colors you are working with, check out this color wheel:
http://www.colorspire.com/rgb-color-wheel/
I want to start with blue, so I use 255 for normalization.
function temp_color($temp){
$start = 40;
$end = 85;
$normal = round(255-((($temp - $start)/($end-$start))*255));
$color = "hsl($normal, 100%, 30%);";
$span = "<span style=\"color: $color\">$temp</span>";
return $span;
}