Group variables and loop through them - php

When I just had single variables I used the compact array function to create an array containing variables and their values and looped through them, but now I have multiple variables in a 'group' to loop through:
$details_room_name_1
$details_room_photo_1
$details_room_capacity_seated_1
$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2
$details_room_name_2
$details_room_photo_2
$details_room_capacity_seated_2
I want to loop through each 'GROUP' (room) of variables at a time
loop
echo room name
print_r room photo array
echo capacity

Using array is better (the best) solution for this task, but if the data structure has to be as you wrote (I don´t know Wordpress), you can use st. like this ugly code.
<?php
$details_room_name_1 = 'room 1';
$details_room_photo_1 = 'photo 1';
$details_room_capacity_seated_1 = 1;
$details_room_name_2 = 'room 2';
$details_room_photo_2 = 'photo 2';
$details_room_capacity_seated_2 = 5;
$details_room_name_3 = 'room 3';
$details_room_photo_3 = 'photo 3';
$details_room_capacity_seated_3 = 8;
for ($i = 1; $i <= 10; $i++) {
if (!isset(${'details_room_name_' . $i})) continue;
echo 'room name: ' . ${'details_room_name_' . $i} . '<br>';
echo 'room photo: ' . ${'details_room_photo_' . $i} . '<br>';
echo 'room capacity: ' . ${'details_room_capacity_seated_' . $i} . '<br><br>';
}
/*
returns
room name: room 1
room photo: photo 1
room capacity: 1
room name: room 2
room photo: photo 2
room capacity: 5
room name: room 3
room photo: photo 3
room capacity: 8
*/

Related

Inventory product computation and conversion

I am coding inventory of products. Now I am in the process of computing or converting the items into a larger unit.
For example:
Product A: 1 box = 12 bottles
The user can input a data like 3 boxes and 13 bottles when adding a transaction. And the new value for Product A will be 3 boxes and 13 bottles in storage. Data will save into database tbl_transaction.
How can I automatically turn/convert the items as a whole like 4 boxes and 1 bottle in storage to add in my tbl_storage?
I have tried this formula but I am afraid it is not accurate when the number of bottles is in the decimal point.
$bottles = 13;
$box = 12;
$remaining_in_bottle = number_format($bottles / $box);// this will only convert the bottle into box (also tried float but not sure what I am doing)
$total_box = 3 + ???;
echo $total_box." boxes and ".$remaining_in_bottle ." bottles in storage
I am assuming the user is inputing just digits as values for boxes and bottles, but if not you will simply need to extract these values from the string before performing the following calculations:
Code: (Demo)
$bottles_per_box=12;
$user_input_bottles=13;
$user_input_boxes=3;
if($user_input_bottles>$bottles_per_box){
// add truncated integer to box count. DO NOT USE ROUND(), USE FLOOR()
$user_input_boxes+=floor($user_input_bottles/$bottles_per_box);
// store remainder after division
$user_input_bottles=$user_input_bottles%$bottles_per_box;
// ^-- modulo operator
}
echo "New Bottles Total: $user_input_bottles\n";
echo "New Boxes Total: $user_input_boxes\n";
Output:
New Bottles Total: 1
New Boxes Total: 4
I assume that you want to input different for tbl_transaction and tbl_storage.
CODE
//Max bottle per box
$box_max_bottles = 12;
//User Input
$input_box = 3;
$input_bottle = 13;
//Transaction
$transaction = (($input_box > 1) ? $input_box . ' boxes' : $input_box . ' box')
. ' and ' . (($input_bottle > 1) ? $input_bottle. ' bottles' : $input_bottle. ' bottle'). ' in storage';
//Data will save into database tbl_transaction
echo $transaction;
//Get the remainder which is the remaining bottle
$total_bottle = $input_bottle % 12;
//Get the total boxes and divide the bottle into 12
$total_box = floor($input_box + ($input_bottle / 12));
echo "<br />";
//Storage
$storage = (($total_box > 1) ? $total_box . ' boxes' : $total_box . ' box')
. ' and ' . (($total_bottle > 1) ? $total_bottle . ' bottles' : $total_bottle . ' bottle'). ' in storage';
//Data will save into database tbl_storage
echo $storage;
OUTPUT
Transaction
3 boxes and 13 bottles in storage
Storage
4 boxes and 1 bottle in storage

PHP - create a tournament results order from array

Consider I have a following array of total scores, with each value being a score of a player in a tournament.
$total_scores = array(350,200,150,150,75,75,75,0);
I need to create a table, which lists the players with correct positions, if they have the same score, the listing should reflect this, ie.:
1. Player 1 350
2. Player 2 200
3.-4. Player 3 150
3.-4. Player 4 150
5.-7. Player 5 75
5.-7. Player 6 75
5.-7. Player 7 75
8. Player 8 0
I tried to do something with
foreach ($total_scores as $total_score) {
$no_of_occurrences = array_count_values($total_scores)[$total_score];
}
But cannot figure out how to build the correct positions numbering.
<?php
$scores = array(350,200,150,150,75,75,75,0); //assuming you have sorted data otherwise you need to sort it first
$count = array();
$startIndex = array();
$endIndex = array();
$len = count($scores);
for($i = 0; $i < $len; $i++){
if(!isset($count[$scores[$i]])){
$count[$scores[$i]] = 1;
$startIndex[$scores[$i]] = $endIndex[$scores[$i]] = $i+1;
}else{
$count[$scores[$i]]++;
$endIndex[$scores[$i]] = $i+1;
}
}
$i = 1;
foreach($scores as $s){
echo $startIndex[$s].'.';
if($startIndex[$s] != $endIndex[$s]){
echo '-'.$endIndex[$s].'.';
}
echo ' Player '.$i.' '.$s."\n"; //if newline not works try echoing <br>
$i++;
}
Working Demo
For this Array needs to be sorted in descending order
$total_scores = array(350, 200, 150, 150, 75, 75, 75, 0);
rsort($total_scores);
$no_of_occurrence = array_count_values($total_scores);
array_unshift($total_scores, ""); // For starting count from 1
unset($total_scores[0]); // For starting count from 1
$i = 1;
foreach ($total_scores as $key => $value)
{
$position = array_keys($total_scores,$value);
if($no_of_occurrence[$value] == 1)
{
echo "Position " . $i . " ";
echo "Player " . $i . " " . $value . " ";
}
else
{
echo "Position " . $position[0] . " - " . end($position) . " ";
echo "Player " . $i . " " . $value . " ";
}
$i++;
echo "<br>";
}
Output of above code :
Position 1 Player 1 350
Position 2 Player 2 200
Position 3 - 4 Player 3 150
Position 3 - 4 Player 4 150
Position 5 - 7 Player 5 75
Position 5 - 7 Player 6 75
Position 5 - 7 Player 7 75
Position 8 Player 8 0

PHP - Easiest Way Of Doing This?

Im checking a column called seasons in MySQL using PDO but how would I go around to check how much is in seasons and echo depending on what it contains for example, lets say it is 3, it would output all of this in one echo:
Season 1
Season 2
Season 3
But what if it checks some other row and that row's season contains 5 I would need it to echo:
Season 1
Season 2
Season 3
Season 4
Season 5
This is all being done in one file index.php and its main dependancy to load is a parameter called ?name= basically the name determines what row to do all this checking on.
How would I do this?
Update:
Season 1
Season 2
Season 3
Season 4
Update:
$seasons = 1;
while (isset(${'dl720p' . $seasons})) $seasons++;
for ($i = 1; $i < $seasons; $i++)
$download = '<a download class="download-torrent button-green-download-big" onclick="window.open(this.href,\'_blank\');return false;" target="_blank" href="' .$dl . ${'dl720p' . $i} . $ref. '"><span class="icon-in"></span>Season ' . $i . '</a>' . "\n";
So you're outputting the links based on how many there are? Try this:
<?php
$dl720p1 = 'one';
$dl720p2 = 'two';
$dl720p3 = 'three';
$dl720p4 = 'four';
$dl720p5 = 'five';
$seasons = 6;
$dl = 'a';
$ref = 'b';
$download = '';
for ($i = 1; $i <= $seasons; $i++)
$download .= 'Season ' . $i . '' . "\n";
echo $download;
Output:
Season 1
Season 2
Season 3
Season 4
Season 5

Cutting text from file

I have the following text file:
::: Student Exam :::
Name: John Cage
Score: 5
Witness: Maria McCain
::: End Exam :::
::: Student Exam :::
Name: John Cage
Score: 5
Witness: Calvin Gilbert
::: End Exam :::
I'm parsing it using this code:
$db = file_get_contents(dirname(__FILE__) . '/exams.txt', TRUE);
$nl = "\r\n";
preg_match_all("|::: Student Exam :::(.*?)::: End Exam :::|s", $db, $exams);
foreach($exams[1] as $exam) {
preg_match("|Name: (.*?)$nl|s", $exam, $name);
preg_match("|Score: (.*?)$nl|s", $exam, $score);
preg_match("|Witness: (.*?)$nl|s", $exam, $witness);
if($score[1] < 4) {
// Something Here
}
}
I need, if the score is under 4, the exam must be removed from the file. How this can be done?
Create an empty array
$goodExams = array()
And push exams into it:
if($score[1] >= 4) {
$goodExams[] = $exam;
}
Or:
if($score[1] >= 4) {
$goodExams[] = array('name' => $name[1], 'score'=>$score[1], 'witness'=>$witness[1]);
}
$newTxt = "";
foreach($goodExams as $exam){
$newTxt.="::: Student Exam :::" . PHP_EOL;
// concatenae your data here
$newTxt.="::: End Exam :::" . PHP_EOL;
}
file_put_contents($filename, $newTxt)
After that you can process the goodExams array and dump your textfile.

how to translate array information into statement in php?

I am working on website that suppose to compare products. So I have reached to this following array
Array ( [iPhone 4 8GB Black] => 319 [iPhone 4S] => 449 [iphone 5] => 529 )
the key of the array is product name and the value of the array is the price. now i want to translate this array into statements like
iphone 4 8GB Black is cheapest!
iPhone 48GB Black is £130(calculation:449-319) cheaper than iphone 4S.
iPhone 48GB Black is £210(calculation:529-319) cheaper than iphone 5.
iPhone 4S is £80(calculation:529-449) cheaper than iphone 5.
iphone 5 is most expensive product from your chosen list.
Please help me on how to output those statements from an array. Your suggestion to do something else with this array in-terms of comparing would also be great. Thank you.
First, you have to sort your array with asort (in order to keep the association between your index and your values, and sort on values).
asort($yourArray);
Then, as your array is sorted, you can isolate price and names.
$names = array_keys($yourArray);
$prices = array_values($yourArray);
At this point you have 2 numerical indexed array containing your label and your prices and these 2 arrays are synchronized.
Finally, you just have to loop from 0 to the length of your array (one of them, its the same size) and made your process:
for($i = 0 ; $i < count($names) ; $i++)
{
if ($i == 0)
{
// First product -> cheapest
echo "The product " . $names[$i] . " is cheapest";
}
else if ($i == (count($names) - 1))
{
// Last product, the most expensive
echo "The product " . $names[$i] . " is the most expensive product of the list";
}
else
{
// calculate the diff between current product and first product
$diff = $price[$i] - $price[0];
echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[0];
}
}
This example make all comparision to the first product.
If you need all combination, it is a little more complexe, you have to make a double loop:
// Hard print the first product
echo "The product " . $names[0] . " is the cheapest";
// Make all possible comparisions
for($j = 0 ; $j < (count($names) - 1) ; $j++)
{
for($i = ($j+1) ; $i < count($names) ; $i++)
{
// calculate the diff between current product and first product
$diff = $price[$i] - $price[$j];
echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[$j];
}
}
// Hard print the last product
echo "The product " . $name[count($names) - 1] . " is the more expensive";

Categories