Divide list in three columns - php

I have list of values that I want to fetch from my database. List could be long so I want to divide into two columns if it has over 15 items and to three columns if it has over 30. How can I break it in 3 columns. Eg..
01 | 12 | 23
02 | 13 | 24
03 | 14 | 25
04 | 15 | 26
05 | 16 | 27
06 | 17 | 28
07 | 18 | 29
08 | 19 | 30
09 | 20 | 31
10 | 21 |
11 | 22 |
For now i'm using tables and it has huge if-nest at the beginning of every loop
$result = mysql_query("SELECT namecount FROM table WHERE name='$myvar'");
if (!$result)
echo 'MySQL Error: ' . mysql_error();
else
{
while ($row = mysql_fetch_array($result))
{
$namecount= $row['namecount'];
for($i=1;$i<=$namecount;$i++)
{
if($namecount>15)
{
if($i==1)
echo "\n<table><tr><td width=\"200px\">";
if($namecount%2==0)
{
if($i==$namecount/2)
echo "</td>\n<td>";
}
else
{
if($i==($sailiot+3)/2)
echo "</td>\n<td>";
}
}
//Print content here
if($namecount>15)
{
if($namecount%2!=0 && $i==$namecount)
echo "<h3> </h3><p> <br> </p>"; //if last item and count is odd, print empty item
if($i==$namecount)
echo "\n</td></tr></table>\n";
}
}
}
}
This (kinda) works with two columns, but what about three?

I would extract <tr>, </tr> out of the inner loop, this saves additional ifs. For splitting into multiple columns, you can calculate the number of items in a column and introduce a second intra column variable to keep track of:
while ($row = mysql_fetch_array($result)) {
$namecount = $row['namecount'];
// calculate items per column
$columns = 1;
if ($namecount > 15)
$columns = 2;
if ($namecount > 30)
$columns = 3;
$items = $namecount / $columns;
if ($namecount % $columns > 0)
++$items;
echo "\n<table><tr><td width=\"200px\">";
for ($i = 1, $j = 1; $i <= $namecount; $i++, $j++) {
if ($j > $items) {
echo "</td>\n<td>";
$j = 1; // reset for new column
}
// Print content here
}
if ($namecount % 2 != 0) {
// if count is odd, print empty item
echo "<h3> </h3><p> <br> </p>";
}
echo "\n</td></tr></table>\n";
}

you maybe can try this
$result = mysql_query("SELECT namecount FROM table WHERE name='$myvar'");
if (!$result)
echo 'MySQL Error: ' . mysql_error();
else
{
while ($row = mysql_fetch_array($result))
{
$namecount= $row['namecount'];
for($i=1;$i<=$namecount;$i++)
{
if($namecount<=15){
echo "<table><thead><tr><th>".$your_variable_data."</th></tr></thead>";}
else if ($namecount >15 and $namecount <=30){
echo "<thead><tr><th>".$your_variable_data."</th></tr></thead></table>";
}
}
}
its not tested but it should work for 3 columns if you want more just add else if .
here a demo how it will be
http://jsfiddle.net/TCJjj/107/

use css3 multi column property
<style>
.namecount {
-moz-column-count:3; /* Firefox */
-webkit-column-count:3; /* Safari and Chrome */
column-count:3;
}
</style>
<div class="namecount">
Long Text
</div>

I found that CSS3 multi-columns was horribly inconsistent between browsers, and very buggy (elements with float:left, white-space:nowrap, etc. cause it to break).
So I wrote the following brute-force collator that retains key=>value pairs.
// vars
$list = array('a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z');
$columns = 3;
// sort it
$count = count($list);
$base = ceil($count/$columns);
$keys = array_keys($list);
for ($i=0;$i<$columns;$i++) {
for ($j=0;$j<$base;$j++) {
if (!empty($keys)) {
$col[$i][] = array_shift( $keys );
}
}
}
$sorted = array();
for ($j=0;$j<$base;$j++) {
for ($i=0;$i<$columns;$i++) {
if (isset($col[$i][$j])) {
$sorted[$col[$i][$j]] = $list[$col[$i][$j]];
}
}
}
// check output
echo '<div style="float:left;margin-right:20px"><h3>ORIGINAL</h3>';
foreach ($list as $k=>$v) echo $k .' = '. $v.'<br>';
echo '</div>';
echo '<div style="float:left"><h3>SORTED</h3>';
foreach ($sorted as $k=>$v) echo $k .' = '. $v .'<br>';
echo '</div>';

Related

Reading and writing a text file with the results of tournament matches with PHP

Group G of The Champions League the results of football competition:
RB Leipzig;AS Monaco;draw
FC Porto;Besiktas JK;loss
Besiktas JK;RB Leipzig;win
AS Monaco;FC Porto;loss
AS Monaco;Besiktas JK;loss
RB Leipzig;FC Porto;win
Besiktas JK;AS Monaco;draw
FC Porto;RB Leipzig;win
Besiktas JK;FC Porto;draw
AS Monaco;RB Leipzig;loss
FC Porto;AS Monaco;win
RB Leipzig;Besiktas JK;loss
The result of the match refers to the first team listed.
(Examples:
Besiktas JK;RB Leipzig;win
means that the Besiktas JK beat the RB Leipzig.
AS Monaco FC;Besiktas JK;loss
means that the Besiktas beat the AS Monaco FC.
RB Leipzig;AS Monaco FC;draw
means that the RB Leipzig and AS Monaco FC tied.)
A win earns a team 3 points. A draw earns 1. A loss earns 0.
The outcome should be ordered by points, descending. In case of a tie, teams are ordered alphabetically.
The output should come out like this:
Team | MP | W | D | L | P
Besiktas JK | 6 | 4 | 2 | 0 | 14
FC Porto | 6 | 3 | 1 | 2 | 10
RB Leipzig | 6 | 2 | 1 | 3 | 6
AS Monaco | 6 | 0 | 2 | 4 | 2
However, I can't get the results in terms of rankings and away wins. How can I do it?
#tournament.txt
RB Leipzig;AS Monaco;draw
FC Porto;Besiktas JK;loss
Besiktas JK;RB Leipzig;win
AS Monaco;FC Porto;loss
AS Monaco;Besiktas JK;loss
RB Leipzig;FC Porto;win
Besiktas JK;AS Monaco;draw
FC Porto;RB Leipzig;win
Besiktas JK;FC Porto;draw
AS Monaco;RB Leipzig;loss
FC Porto;AS Monaco;win
RB Leipzig;Besiktas JK;loss
#tournament.php
<?php
$lines = file('tournament.txt');
foreach ($lines as $line) {
$parts = explode(';', $line);
$teams[$parts[0]][] = $parts[2];
$teams[$parts[1]][] = $parts[2];
}
uksort($teams, function ($a, $b) use ($teams) {
$aPoints = 0;
$bPoints = 0;
foreach ($teams[$a] as $result) {
if ($result == 'win') {
$aPoints += 3;
} elseif ($result == 'draw') {
$aPoints += 1;
}
}
foreach ($teams[$b] as $result) {
if ($result == 'win') {
$bPoints += 3;
} elseif ($result == 'draw') {
$bPoints += 1;
}
}
foreach ($teams[$a] as $result) {
if ($result == 'loss') {
$aPoints += 0;
$bPoints += 3;
}
}
foreach ($teams[$b] as $result) {
if ($result == 'loss') {
$aPoints += 3;
$bPoints += 0;
}
}
if ($aPoints == $bPoints) {
return $a <=> $b;
}
return $bPoints <=> $aPoints;
});
$fp = fopen('tournament.txt', 'w');
fwrite($fp, "Team | MP | W | D | L | P
");
foreach ($teams as $team => $results) {
$mp = count($results);
$w = 0;
$d = 0;
$l = 0;
foreach ($results as $result) {
if ($result == 'win') {
$w++;
} elseif ($result == 'draw') {
$d++;
} else {
$l++;
}
}
$p = $w * 3 + $d;
fwrite($fp, sprintf("%-30s| %2d | %2d | %2d | %2d | %2d
", $team, $mp, $w, $d, $l, $p));
}
fclose($fp);
?>
I cannot test your code because I am in PHP Version 5.6.36.
But with the code below which works from PHP 5 I get results.
Including away wins.
<style type="text/css">
table { border-spacing: 0px; }
table th { padding: 5px; border: 1px solid black; }
table td { padding: 3px; border: 1px solid dimgrey; }
</style>
<?
// Initialisation
$infoList = array("MP","W","Wext","D","L","P");
// Open File
$lines = file('tournament.txt');
// For Each Line
foreach ($lines as $line)
{
$parts = explode(';', $line);
// Extraction
$teamA = $parts[0];
$teamB = $parts[1];
$score = $parts[2];
// Initialization
$teamList["$teamA"]["W"] = 0;
$teamList["$teamA"]["Wext"] = 0;
$teamList["$teamA"]["L"] = 0;
$teamList["$teamA"]["D"] = 0;
$teamList["$teamA"]["P"] = 0;
$teamList["$teamA"]["MP"] = (array_key_exists("MP", $teamList["$teamA"]))?bcadd($teamList["$teamA"]["MP"],1,0):1;
// Initialization
$teamList["$teamB"]["W"] = 0;
$teamList["$teamB"]["Wext"] = 0;
$teamList["$teamB"]["L"] = 0;
$teamList["$teamB"]["D"] = 0;
$teamList["$teamB"]["P"] = 0;
$teamList["$teamB"]["MP"] = (array_key_exists("MP", $teamList["$teamB"]))?bcadd($teamList["$teamB"]["MP"],1,0):1;
// Memorisation
$matchList[] = array("teamA"=>$teamA, "teamB"=>$teamB, "score"=>trim($score));
}
// End - For Each Line
// For Each Match
foreach($matchList as $matchKey => $matchValue)
{
// If Team A Win
if($matchValue["score"]=="win")
{
// Memorisation Team A
$teamList["".$matchValue["teamA"].""]["W"] = bcadd($teamList["".$matchValue["teamA"].""]["W"],1,0);
$teamList["".$matchValue["teamA"].""]["P"] = bcadd($teamList["".$matchValue["teamA"].""]["P"],3,0);
}
// If Team A Loss
if($matchValue["score"]=="loss")
{
// Memorisation Team B
$teamList["".$matchValue["teamB"].""]["W"] = bcadd($teamList["".$matchValue["teamB"].""]["W"],1,0);
$teamList["".$matchValue["teamB"].""]["Wext"] = bcadd($teamList["".$matchValue["teamB"].""]["Wext"],1,0);
$teamList["".$matchValue["teamB"].""]["P"] = bcadd($teamList["".$matchValue["teamB"].""]["P"],3,0);
}
// If Equality
if($matchValue["score"]=="draw")
{
// Memorisation Team A
$teamList["".$matchValue["teamA"].""]["D"] = bcadd($teamList["".$matchValue["teamA"].""]["D"],1,0);
$teamList["".$matchValue["teamA"].""]["P"] = bcadd($teamList["".$matchValue["teamA"].""]["P"],1,0);
// Memorisation Team B
$teamList["".$matchValue["teamB"].""]["D"] = bcadd($teamList["".$matchValue["teamB"].""]["D"],1,0);
$teamList["".$matchValue["teamB"].""]["P"] = bcadd($teamList["".$matchValue["teamB"].""]["P"],1,0);
}
}
// Fin - For Each Match
// -------- Display in HTML -------- //
echo "<table>";
echo "<tr>";
echo "<th></th>";
foreach($infoList as $infoKey => $infoValue) { echo "<th>".$infoValue."</th>"; }
echo "</tr>";
// For Each Team
foreach($teamList as $teamName => $teamValue)
{
echo "<tr>";
echo "<td>".$teamName."</td>";
// For Each Type Information
foreach($infoList as $infoKey => $infoValue)
{
echo "<td>".$teamValue["$infoValue"]."</td>";
}
// End - For Each Type Information
echo "</tr>";
}
// End - For Each Team
echo "</table>";
// --------------------------------- //
?>
It may seem a bit heavy but it allows to have a teamList array with all the necessary information

output numbers bold except some

How to produce the following output? All numbers should be bold except 10, 20, 30 and 40.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
My current code is:
<?php
$i = 1;
while($i <= 40) {
$m = ($i % 1);
if($m == 0) {
echo '<b><u>' . $i . '</b></u>';
}
$i++;
}
?>
Simple one:
<?php
for ($i=1;$i<=40;$i++){
if ($i % 10 == 0){
$result .= $i;
}
else{
$result .= "<b>".$i."</b>";
}
}
echo $result;
?>
Update 1:
If your logic is to be corrected then,
<?php
$i = 1;
while($i <= 40) {
$m = ($i % 10); // have to replace 1 by 10
if($m == 0) {
echo $i;
}
else{
echo '<b><u>' . $i . '</b></u>';
}
$i++;
}
?>
You can merge the if ($i%10 == 0) into single statement as well.
<?php
$i=1;
while($i<=40)
{
if ($i%10 == 0){
echo $i;
}
else{
echo '<b><u>'.$i.'</b></u>';
}
$i++;
}
?>
one small Correction From 1st answer #Fakhruddin Ujjainwala
Undefined variable: result
<?php
$result = "";
for ($i=1;$i<=40;$i++){
if ($i % 10 == 0){
$result .= $i;
}
else{
$result .= "<b>".$i."</b>";
}
}
echo $result;
?>

increment counter when value occurs more than once

An example output of the following code may be this:
39 48 39 12 17 39 12
code:
if (mysql_num_rows($filterResult)) {
while ($filterrow = mysql_fetch_array($filterResult)) {
$vidID = $filterrow['routineID'];
...
...
echo "<video id='video$vidID'></video>";
}
}
I need it to output like this:
39 48 39_1 12 17 39_2 12_1
Notice how value 39 occurs three times and value 12 occurs twice.
After the first occurence of a value I need it
formatted like ##_#.
Can you help me code this up?
I appreciate your time and assistnace -
Derek
Use array_count_values like this:-
$array = array(1, 38, 1, 38,35);
print_r(array_count_values($array));
Output:-
Array
(
[1] => 2
[38] => 2
[35] => 1
)
Apply some logic to achieve what you want.
if (mysql_num_rows($filterResult)) {
$tmp = array();
while ($filterrow = mysql_fetch_array($filterResult)) {
$vidID = $filterrow['routineID'];
if(isset($tmp[$vidID]) {
$tmp[$vidID] = $tmp[$vidID] + 1;
$vidID = $vidID . '_' . $tmp[$vidID];
} else {
$tmp[$vidID] = 0;
}
echo $vidID;
}
}
if (mysql_num_rows($filterResult)) {
while ($filterrow = mysql_fetch_array($filterResult)) {
$j=-1;
$vidID = $filterrow['routineID'];
$arr[]=$vidID;
for($i=0;$i<count($arr);$i++){
if($arr[$i]==$vidID)
$j++;
}
if($j==0)
$j="";
else $j="_".$j;
echo $vidID.$j;
}
}
Here is the code:
$array1 = array(39,48,39,12,17,39,12);
$array2 = array(39,48,39,12,17,39,12);
foreach($array1 as $value){
$counts1 = array_count_values($array1);
$counts2 = array_count_values($array2);
if(!empty($counts2[$value])){
if ($counts1[$value] > 1){
$count = $counts1[$value] - $counts2[$value] + 1;
if($count > 1) {
echo $value.'_'.($count - 1).' ';
} else {
echo $value.' ';
}
} else {
echo $value.' ';
}
array_shift($array2);
}
}
Here is the PHP fiddle

Displaying Rows of HTML Elements in Vertical Rows

I want to show a list of categories in my Virtuemart webshop vertically sorted the same way as shown in this demonstration:
http://www.inkplant.com/code/mysql-vertical-sort.php
So I borrowed the code:
<?php
$cols = 4; //number of columns, you can set this to any positive integer
$values = array();
$result = mysql_query("SELECT * FROM states ORDER BY name");
$numrows = mysql_num_rows($result);
$rows_per_col = ceil($numrows / $cols);
for ($c=1;$c<=$cols;$c++) { $values['col_'.$c] = array(); }
$c = 1;
$r = 1;
while ($row = mysql_fetch_assoc($result)) {
$values['col_'.$c][$r] = stripslashes($row['name']);
if ($r == $rows_per_col) { $c++; $r = 1; } else { $r++; }
}
echo "<table>" ;
for ($r=1;$r<=$rows_per_col;$r++) {
echo "<tr>" ;
for ($c=1;$c<=$cols;$c++) { echo "<td>".$values['col_'.$c][$r]."</td>" ; }
echo "</tr>" ;
}
echo "</table>" ;
unset($values);
?>
I then tried to modify it in my Virtuemart category template file with this result:
<?php
$cols = 3; //number of columns, you can set this to any positive integer
$values = array();
$numrows = $precounterdigit;
$rows_per_col = ceil($numrows / $cols);
for ($c=1;$c<=$cols;$c++) { $values['col_'.$c] = array(); }
$c = 1;
$r = 1;
foreach ( $this->category->children as $category ) {
$catname = $category->category_name;
$caturl = JRoute::_ ( 'index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $category->virtuemart_category_id );
$values['col_'.$c][$r] = '<div class="category floatleft'.$category_cellwidth.'">
<div class="spacer"><h2>
<a href="'.$caturl.'" title="'.$catname.'">
'.$catname.'<br /></a></h2>
</div></div>';
if ($r == $rows_per_col) { $c++; $r = 1; } else { $r++; }
}
echo '<div class="tablediv">' ;
for ($r=1;$r<=$rows_per_col;$r++) {
echo '<div class="row">' ;
for ($c=1;$c<=$cols;$c++) { echo $values['col_'.$c][$r]; }
echo '</div>' ;
}
echo '</div>' ;
unset($values);
?>
It actually shows perfectly in the category view if the number of categories are dividable by 3 or dividable by 3 -1. Meaning that it shows correctly if there are 3, 5, 6, 8, 9, 11, 12 etc... categories on the page.
If the number of categories equals a number that is dividable by 3 +1 then it shows in a weird way..
Here is an example of how it shows when there are 9 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat8
Cat3 | Cat6 | Cat9
Here is an example of how it shows when there are 8 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat8
Cat3 | Cat6 |
And here is an example of how it shows when there are 7 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat3
Cat6 |
I really cannot figure this one out, so I hope someone can help me a little bit here..
Just try this, Sure you can change cols and rows.
<?php //user210424
$cols = 3;
$rows = 3;
$j = 0;
$array = array("ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE");
for($i=1; $i<=$cols; $i++) {
echo "<div class='col' style='float:left;'>";
for($j; $j<$rows*$i; $j++) {
echo "<div class='row'>".$array[$j]."</div>";
}
echo "</div>";
}
?>

Reversing page navigation on PHP

Can anyone help me with reversing this PHP page navigation?
Current script setting shows this format: [0] | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ... 14 • Forward > • End >>>
But I really need it to reverse for this format: [14] | 13 | 12 | 11| 10 | 9 | 8 | 7 | 6 ... 0 • Back > • Start >>>
Here is the PHP code:
<?
$onpage = 10; // on page
function page(){
if(empty($_GET["page"])){
$page = 0;
} else {
if(!is_numeric($_GET["page"])) die("Bad page number!");
$page = $_GET["page"];
}
return $page;
}
function navigation($onpage, $page){
//----------------
$countt = 150;
$cnt=$countt; // total amount of entries
$rpp=$onpage; // total entries per page
$rad=4; // amount of links to show near current page (2 left + 2 right + current page = total 5)
$links=$rad*2+1;
$pages=ceil($cnt/$rpp);
if ($page>0) { echo "<<< Start <font color='#CCCCCC'>•</font> < Back <font color='#CCCCCC'>•</font>"; }
$start=$page-$rad;
if ($start>$pages-$links) { $start=$pages-$links; }
if ($start<0) { $start=0; }
$end=$start+$links;
if ($end>$pages) { $end=$pages; }
for ($i=$start; $i<$end; $i++) {
echo " ";
if ($i==$page) {
echo "[";
} else {
echo "<a href=\"?page=$i\">";
}
echo $i;
if ($i==$page) {
echo "]";
} else {
echo "</a>";
}
if ($i!=($end-1)) { echo " <font color='#CCCCCC'>|</font>"; }
}
if ($pages>$links&&$page<($pages-$rad-1)) { echo " ... ".($pages-1).""; }
if ($page<$pages-1) { echo " <font color='#CCCCCC'>•</font> Forward > <font color='#CCCCCC'>•</font> End >>>"; }
}
$page = page(); // detect page
$navigation = navigation($onpage, $page); // detect navigation
?>
for ($i=$end; $i>$start; $i--) {
echo " ";
if ($i==$page) {
echo "[";
} else {
echo "<a href=\"?page=$i\">";
}
//othercode
}
I found the solution for my question. Here is a link to reversed page navigation: php page navigation by serial number

Categories