Why wont the chosen option reflect in the PHP code I wrote? - php

Basically it's supposed to get the user submitted value of the array size, and the method they want to calculate with the array from the drop down. the php successful gets the code from the array size but always sees the field with the dropdown as "mean" no matter which I select.
forms5.html:
`<html>
<head>
</head>
<body style="background-color: rgb(192, 192, 192);">
<div class="container" style="background-color: rgb(165, 165, 165); width: 575px; height: 250px; border: ridge; border-color: rgb(209, 209, 209);">
<form name = "form1" method = "get" action = "actions_5.php">
<div class = "form-group" style=" padding-left: 10px; padding-right: 10px; padding-top: 10px;">
<label><h2>Enter size of an array</h2></label> <br>
<input type = "number" name = "array_size" placeholder="Type in an integer">
</div>
<br>
<div style="padding-left: 10px; padding-right: 10px;">
<label><b>Select an option</b></label>
<select name = "option" class="form-control">
<option value="mean">Calculate Mean</option>
<option value="median">Calculate Median</option>
<option value="mode">Calculate Mode</option>
</select>
</div>
<div style="padding: 10px;">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</body>
</html>'
actions_5.php:
'<?php
session_start();
echo "<html>";
echo "<head>";
echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
';
echo "</head>";
echo "<body style='background-color: lightgray'>";
//store variables
$choice = $_GET['option'];
$size = $_GET['array_size'];
//create array
for($i = 0; $i < $size; $i++) {
$array[$i] = mt_rand(1,10);
}
echo "<div style = 'color: green; padding-top: 160px'><center><h3>Initialized array --><h3></center></div>";
echo "<br>";
echo"<center><div style = 'color: red; font-size: 35px; padding-top: 10px'>";
for($i = 0; $i < $size; $i++) {
echo"<b>$array[$i] </b>";
}
echo"</div></center>";
echo"<br>";
//if statements
echo"<center><div style = padding=top: 10px; front-size: 35px>";
if($choice = "mean") {
$mean = array_sum($array) / count($array);
echo"<p style = 'color:crimson'><b>Mean = $mean</b></p>";
} else if($choice = "mode") {
sort($array);
sort($array, $size);
$max = 1;
$mode = $array[0];
$current = 1;
for($i = 0; $i < $size; $i++){
if($array[$i] == $array[$i] - 1){
$current++;
}
else {
if($current > $max) {
$max = $current;
$mode = $array[$i - 1];
}
$current = 1;
}
}
if($current > $max) {
$max = $current;
$mode = $array[$size - 1];
}
if($max = 1) {
echo"<p style = 'color:teal'><b>There is no mode in the set.</b></p>";
} else{
echo"<p style = 'color:teal'><b>Mode = $mode</b></p>";
}
} else {
rsort($array);
$n = count($array) / 2;
$median = $array($n);
echo"<p style = 'color:blue'><b>Median = $median</b></p>";
}
echo"</div></center>";
echo "</body>";
echo "</html>";
?>'

Related

How to give alternating table rows different background colors in while loop and CSS (not using :nth-child() selector)

I am trying to put background colors in a PHP while loop table with CSS. I can't find out how to write a code to change the first row and first column (header) colors and also change the color diagonally below from the top left.
I know that the table header can be changed by using <th> in CSS but I'm not sure how to use <th> in PHP. I did some research and the only solution for getting this multiplication table is below.
NOTE nth-child() selector is not allowed.
This is what my code looks like:
<!DOCTYPE html>
<html>
<head>
<title>table</title>
</head>
<body>
<table border = "1">
<?php
$x = 1; //rows
echo "<table border = '1'>\n";
while ( $x <= 12 ) {
echo "\t<tr>\n";
$y = 1;//columns
while ( $y <= 12 ) {
echo "\t\t<td>$x x $y = " . $x * $y . "</td>\n";//the result of the multiplication
$y++;
}
echo "\t</tr>\n";
$x++;
}
echo "</table>";
?>
</tr>
</div>
</table>
</body>
CSS code as below.
<style>
table {
width: 100%;
height: 400px;
font-family: arial, sans-serif;
border-collapse: collapse;
}
tr{
background-color: #FF8A65;
}
</style>
</html>
And this is what it should look like:
Do you mean something like this
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<style>
table {
width: 100%;
height: 400px;
font-family: arial, sans-serif;
border-collapse: collapse;
}
tr{
background-color: #82BFBF;
}
</style>
</head>
<body>
<table border = "1">
<?php
$x = 1; //rows
echo "<table border = '1'>\n";
while ( $x <= 12 ) {
if ( $x == 1)
echo "\t<tr style='background-color:green'>\n";
$y = 1;
while ( $y <= 12 ) {
$bgc = '';
if ( ($y == 1 || $x == 1) && $y != $x) {
$bgc = "style='background-color:green'";
} elseif ( $y == $x ) {
$bgc = "style='background-color:red'";
} elseif ($y > 1 && $x % 2){
$bgc = "style='background-color:#FF8A65'";
}
echo "\t\t<td $bgc>$x x $y = " . $x * $y . "</td>\n";
$y++;
}
echo "\t</tr>\n";
$x++;
}
echo "</table>";
?>
</tr>
</div>
</table>
</body>
</html>

Upload uploading dark photo

I have a system for registering products, where the part of including photos is like this:
The code that on the part of the photos is like this:
$visualizar = '<table class="table table-bordered">
<tr>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Tamanho <i class="fa fa-plus-circle" aria-hidden="true"></i></td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Quantidade</td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">EAN</td>
</tr>';
$sql = mysqli_query($this->conexao,"SELECT * FROM loja_tamanho_grades WHERE IdGrades = '".$grades."';");
///$c = 0;
while($isfast = mysqli_fetch_assoc($sql))
{
$sqlTamanhos = mysqli_query($this->conexao,"SELECT * FROM loja_tamanhos WHERE IdTamanhos = '".$isfast["IdTamanhos"]."';");
$isfastTamanhos = mysqli_fetch_assoc($sqlTamanhos);
$visualizar .= '<tr>
<td style="font-weight: bold; text-align: center; font-size: 20px; font-style:Arial">
<input type="hidden" name="GradesEscolhidas[]" value="'.$grades.'">
<input type="text" name="TamanhosEscolhidos[]" style="border: 0px; width: 50px; text-align: center" readonly value="'.$isfastTamanhos["Tamanhos"].'">
</td>
<td>
<input type="number" name="QtdEscolhidos[]" class="form-control" min="0" oninput="this.value = Math.abs(this.value)" value="0">
</td>
<td>
<input type="text" name="EANEscolhidos[]" class="form-control" maxlength="17" style="width: 100%">
</td>
</tr>';
}
$visualizar .= '<tr>
<td colspan="3" class="text-left">
<label for="fotos" class="upload">Selecionar fotos <i class="fa fa-plus-circle fa-lg" aria-hidden="true"></i></label>
<input type="hidden" name="GradesFotos[]" value="'.$grades.'">
<input id="fotos" type="file" name="Fotos[]['.$grades.']" multiple>
</td>
</tr>';
//$c++;
$visualiza[] = $visualizar;
echo json_encode($visualiza);
When the user clicks sign up, it is directed to the method below:
if($_POST["Submit"] == "Cadastrar"){
$fotos = $_FILES["Fotos"];
$fotosTemp = $_FILES["Fotos"]["tmp_name"];
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados,$fotos,$fotosTemp);
}
And the method cadastrarProdutos():
public function cadastrarProdutos(array $dados,$fotos,$fotosTemp)
{
...
$gradesEscolhidas = $dados["GradesEscolhidas"];
for($f = 0; $f < count($fotos['name']); $f++)
{
foreach($fotos['name'][$f] as $key => $value){
$fotosProd = $value;
$tempProd = $fotos['tmp_name'][$f];
$extensoesProd = array('png', 'jpg', 'jpeg','JPG');
$validarProd = pathinfo($fotosProd, PATHINFO_EXTENSION);
list($nomeFotoProd, $extensaoFotoProd) = explode($validarProd, $fotosProd);
$data = date("Y-m-d H:i");
$nomeFotoProd = md5($nomeFotoProd).".".$validarProd;
if($fotosProd == $fotoPrincipal[0])
{
$nomeFotoPrinc = $nomeFotoProd;
}
if(!in_array(strtolower($validarProd), $extensoesProd))
{
$_SESSION["ErroFoto"] = "Extensões permitidas: png e jpg";
$_SESSION["Erro"] = time() + 2;
}
else
{
move_uploaded_file($tempProd, '../../site/produtos/'.$nomeFotoProd);
$diretorioNormal = "../../site/produtos/";
$fotoDir = $diretorioNormal.$nomeFotoProd;
list($largura, $altura) = getimagesize($fotoDir);
if($validarProd == 'jpg' || $validarProd == 'jpeg' || $validarProd == 'JPG')
{
$imagem = imagecreatefromjpeg($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagejpeg($miniatura,$fotoDir,9);
}
if($validarProd == 'png')
{
$imagem = imagecreatefrompng($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagepng($miniatura,$fotoDir,9);
}
$query = "INSERT INTO loja_fotos_produtos(IdProdutos,IdGrades,Fotos) VALUES(?,?,?);";
$stmt = mysqli_prepare($this->conexao,$query);
mysqli_stmt_bind_param($stmt,"sss",$idProduto,$key,$value);
mysqli_stmt_execute($stmt);
if(mysqli_affected_rows($this->conexao) > 0)
{
$_SESSION["Sucesso"] = time() + 5;
}
}
}
}
}
Registration usually occurs, but the photos are as follows. How can I fix this?

How do I align a list of links/picture on the right side of the page, and stop them from overlapping?

I want to generate a list of links to other pages for my website (using a mix of PHP/HTML/CSS) and align them on the right side of the page without them overlapping. I am able to generate the links/pictures, but the problem I am having is they overlap on top of each other when I try to use position absolute.
<style>
body{
background: lightblue;
margin: 25px;
}
.title{
font-size: 20px;
}
.recipe{
width: 60%;
}
.related{
position: absolute;
float: right;
right: 10px;
width: 25%;
list-style-position: inside;
}
.a{
float: right;
right: 5px;
}
.relatedImages{
}img{
width: 15%;
height: 17%;
}
</style>
<title><?php $recipeInfo['title']; ?></title>
<body>
<br>
<?php
//Title and image of recipe
echo '<br><br><div class="title">' .$recipeInfo['title']. '</div><br>
<div class="mainImage"><image src="' . $recipeInfo['image']. '"> </div>
<br><h2> Ingredients </h2>';
//Unfinished (Needs to be styled correctly)
//Generating related links with clickable images
for($r = 0; $r < $relatedLinks[$r]; $r++){
echo '<div class = "related">
<a href = "recipeInfo.php?id='.$relatedLinks[$r]['id']. '">'.$relatedLinks[$r]['title'].'<br>
<image src = "https://spoonacular.com/recipeImages/' . $relatedLinks[$r]['image'] . '"></a>
<br>
</div>';
};
;
//Loop that generates a list of the ingredients used
for($i = 0; $i < $recipeInfo['extendedIngredients'][$i]; $i++){
$amount = $recipeInfo['extendedIngredients'][$i]['amount'];
$unit = $recipeInfo['extendedIngredients'][$i]['unit'];
$ingrName = $recipeInfo['extendedIngredients'][$i]['name'];
echo '<div class = "ingredients">' . $amount , " " , $unit , " " , $ingrName .' </div>';
}
//Instructions with error handling for no instructions found
$instructions = $recipeInfo['instructions'];
if($instructions == ""){
$instructions = "Whoops, there are no available instructions for this recipe.";
}
echo '<br><h2> Insructions </h2>
<div class="recipe">' . $instructions . '</div><br>';
//Unfinished, but will hopefully print a better list of instructions than just a dense paragraph
//for($j = 0; $j < sizeOf($recipeInstr); $j++){
// echo '<h3>' .$recipeInstr[$j]['name'].'</h3>';
// for($n = 0; $n < $recipeInstr[$j]['steps']; $n++){
// echo '<div class="instruction">'. $n , " " , $recipeInstr[$j]['steps'][$n]['step'] . '<div>';
// }
//}
?>
</body>
</html>
The intended effect I am going for is one similar to how youtube has related videos on the right side of the page.
Well cou could try this code:
<body>
<br>
<div class="maincontent">
<div class="main">
<?php
//Title and image of recipe
echo '<br><br><div class="title">' .$recipeInfo['title']. '</div><br>
<div class="mainImage"><image src="' . $recipeInfo['image']. '"> </div>
<br><h2> Ingredients </h2>';
//Loop that generates a list of the ingredients used
for($i = 0; $i < $recipeInfo['extendedIngredients'][$i]; $i++){
$amount = $recipeInfo['extendedIngredients'][$i]['amount'];
$unit = $recipeInfo['extendedIngredients'][$i]['unit'];
$ingrName = $recipeInfo['extendedIngredients'][$i]['name'];
echo '<div class = "ingredients">' . $amount , " " , $unit , " " , $ingrName .' </div>';
}
//Instructions with error handling for no instructions found
$instructions = $recipeInfo['instructions'];
if($instructions == ""){
$instructions = "Whoops, there are no available instructions for this recipe.";
}
echo '<br><h2> Insructions </h2>
<div class="recipe">' . $instructions . '</div><br>';
//Unfinished, but will hopefully print a better list of instructions than just a dense paragraph
//for($j = 0; $j < sizeOf($recipeInstr); $j++){
// echo '<h3>' .$recipeInstr[$j]['name'].'</h3>';
// for($n = 0; $n < $recipeInstr[$j]['steps']; $n++){
// echo '<div class="instruction">'. $n , " " , $recipeInstr[$j]['steps'][$n]['step'] . '<div>';
// }
//}
?>
</div>
<div class="sidelinks">
<?php
//Unfinished (Needs to be styled correctly)
//Generating related links with clickable images
for($r = 0; $r < $relatedLinks[$r]; $r++){
echo '<div class = "related">
<a href = "recipeInfo.php?id='.$relatedLinks[$r]['id']. '">'.$relatedLinks[$r]['title'].'<br>
<image src = "https://spoonacular.com/recipeImages/' . $relatedLinks[$r]['image'] . '"></a>
<br>
</div>';
};
;
</div>
</div>
</body>
</html>
and css code:
<style>
.maincontent {
display: grid;
grid-template-columns: 70% 30%;
}
body{
background: lightblue;
margin: 25px;
}
.title{
font-size: 20px;
}
.recipe{
width: 60%;
}
.related{
list-style-position: inside;
}
.a{
float: right;
right: 5px;
}
.relatedImages{
}img{
width: 15%;
height: 17%;
}
</style>
this should work, i couldnt test it

run php code if $players is between 5 and 9 in third span

Ok i edit my question i think i understand more now how to build a question.
The website: bit DOT ly/1MHItEH
I want to run a php code when span 3 is between 5 & 9.
The code which outputs this is $players and in the bottom there is a html output code
<td><span style='text-shadow: 0 0 10px #ffca00; color: #ffca00; font-size: 20pt;'>". $players ."</span></td>
This php code outputs a html table with different values for every added server.
For example if i add a new server to servers.php it will create a new span for that server with new values. So basicly it reads and outputs different values for every server.
So how can i just run extra php code if the span 3 is between 5 & 9?
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
tr td, tr th { text-align: center !important; }
tr td.motd, tr th.motd { text-align: left !important; }
</style>
</head>
<body style="width: 100%; margin: 0 auto; height: 20px; ">
<table class='table table-bordered table-striped'>
</br>
<?php
error_reporting(0);
function openserveriai() {
}
function closeserveriai() {
}
function getnextstring(&$data) {
$temp="";
$counter=0;
while (ord($data[$counter++])!=0) $temp.=$data[$counter-1];
$data=substr($data,strlen($temp)+1);
return $temp;
}
function getnextbytevalue(&$data) {
$temp=ord($data[0]);
$data=substr($data,1);
return $temp;
}
function addServer($ip) {
$map = '';
$players = '';
$maxplayers = '';
$servername = '';
$output = '';
$live_server = '0';
$packet = '0';
$packet = "\xFF\xFF\xFF\xFFTSource Engine Query\x00";
$live_server = fsockopen("udp://".$ip);
if(!$live_server)
{
$output = "Off";
}
else
{
fwrite($live_server, $packet);
socket_set_timeout($live_server,1,0);
$junk = fread($live_server,5);
$status = socket_get_status($live_server);
$do = 1;
$server_info= "";
while($do)
{
$str_1 = fread($live_server,1);
$server_info .= $str_1;
$status = socket_get_status($live_server);
if($status["unread_bytes"] == 0) {$do = 0;}
}
fclose($live_server);
if (strlen($server_info) > 0)
{
$success = 1;
$junk = getnextstring($server_info);
$servername = getnextstring($server_info);
$map = getnextstring($server_info);
$junk = getnextstring($server_info);
$junk = getnextstring($server_info);
$players = getnextbytevalue($server_info);
}
if ($players != '') {
$players = $players;
} else {
$players = "0";
}
if ($maxplayers != '')
{
$maxplayers = $maxplayers;
}
else
{
$maxplayers = "0";
}
if ($output != "Full" and $players != "0" or $maxplayers != "0")
{
$output = $output;
}
else
{
$output = "<font color='#FF0000'>Offline</font>";
}
if ($map != '')
{
$map = $map;
}
else
{
$map = "--";
$maxplayers = "--";
$players = "--";
}
if ($servername != '') {
$servername = $servername;
}
else
{
$servername = "--";
}
}
if($players == $maxplayers && $players != '--')
{
$players = "" . $players . "";
}
else if($players > $maxplayers-3 && $players != '--')
{
$players = "" . $players . "";
}
else
{
$players = "" . $players . "";
}
if ( strlen($map) > 19 )
{
$map = substr($map, 0, 19) . '...';
}
echo "
<tbody>
<tr style='background: #10130d;'>
";
if ($map == '--')
{
echo "<td><span style='background-color: #b85c5c; border-radius: .25em; padding: .2em .6em .3em; font-weight: bold; color: #fff; font-size: 10pt;'>Offline</i></span></td>";
}
else
{
echo "<td><span style='background-color: #5cb85c; border-radius: .25em; padding: .2em .6em .3em; font-weight: bold; color: #fff; font-size: 10pt; '>Online</i></span></td>";
}
echo "
<td><span style='color: #fff; font-size: 10pt;'>". $ip ."</span></td>
<td><span style='text-shadow: 0 0 10px #ffca00; color: #ffca00; font-size: 20pt;'>". $players ."</span></td>
</tr>
</tbody>
";
}
openserveriai();
include ('servers.php');
closeserveriai();
?>
</table>
</body>
</html>
You can do something like this
<?php
$total = 5;
if ($total >= 5 && $total <= 9) {
//Between 5 and 9
} else {
// Not between 5 and 9
}
?>
<table class='table table-bordered table-striped'>
<tbody>
<tr>
<td><span>First</span></td>
<td><span>Second</span></td>
<td><span><?php echo $total; ?></span></td>
</tr>
</tbody>
</table>
Then you can call that php page with
require('yourpage.php');

displaying csv data in four columns in php

I have complaint.csv file in which data is like below:
1,complaint of health
2,complaint of money
.
.
.
71,complaint of bill
I want to show above data in four columns in PHP such that each column will have equal numbers of rows.
I have tried below code in which I couldn't able to get success.
<?php
$fp = file('../complaint.csv', FILE_SKIP_EMPTY_LINES);
$total_rows = count($fp);
$count = $total_rows;
$first_col = ceil($count/ 4);
$count -= $first_col;
$second_col = ceil($count/ 3);
$count -= $second_col ;
$third_col = ceil($count/ 2);
$forth_col = $count - $third_col ;
while (!feof($fp)) {
$lines[] = fgetcsv($fp, 1024);
}
fclose($fp);
?>
<div class="added">
<div class="column-left">
<?php
for ($i = 0; $i < $first_col; $i++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$i][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$i][0]; ?>" id="<?php print 'checkbox'.$line[$i][0]; ?>" data-toggle="checkbox">
<?php print $line[$i][1]; ?>
</label>
<?php
endforeach;
}
?>
</div>
<div class="column-center">
<?php
$k = $i;
for ($j = 0; $j < $second_col; $j++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$j][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$j][0]; ?>" id="<?php print 'checkbox'.$line[$j][0]; ?>" data-toggle="checkbox">
<?php print $line[$j][1]; ?>
</label>
<?php
endforeach;
$k++;
}
?>
</div>
<div class="column-center-right">
<?php
$m = $k;
for ($l = 0; $l < $third_col; $l++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$l][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$l][0]; ?>" id="<?php print 'checkbox'.$line[$l][0]; ?>" data-toggle="checkbox">
<?php print $line[$l][1]; ?>
</label>
<?php
endforeach;
$m++;
}
?>
</div>
<div class="column-right">
<?php
$n = $k;
for ($p = 0; $p < $forth_col; $p++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$p][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$p][0]; ?>" id="<?php print 'checkbox'.$line[$p][0]; ?>" data-toggle="checkbox">
<?php print $line[$p][1]; ?>
</label>
<?php
endforeach;
$n++;
}
?>
<br/>
</div>
</div>
CSS
<style>
.column-left{ float: left; width: 25%; }
.column-right{ float: right; width:25%; }
.column-center{ float: left; width: 25%; }
.column-center-right{ float: left; width: 25%; }
div.added {
padding: 0px 0px 5px 0px;
font-size: 22px;
font-family: "freightbook";
color: #2a4753;
text-align: left;
}
</style>
I am getting Error like Notice: Uninitialized string offset. The affected lines are between foreach loop
Can anyone please tell me, what went wrong in above code or any other solution of it?
Here's a solution:
Variable number of columns
Unequal number of lines are filled from left to right
Formatting of HTML elements thru styles (CSS)
Input (complaint.csv)
1,complaint of health
2,complaint of money
3,complaint type 3
4,complaint type 4
5,complaint type 5
6,complaint type 6
7,complaint type 7
8,complaint type 8
9,complaint of bill
Code
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('./complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// Page, part 1 --------------------------------------------------------
echo '<html
<head>
<style type="text/css">
BODY { font-family:tahoma,arial,helvetica,sans-serif; font-size:76%; }
.table { background-color: #e0e0e0; }
.break { break:both; border:0; with:1px; }
.column { border:0; float:left; padding:0.333em; }
</style>
</head>
<body>
';
// Page, part 1 --------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[0].'" id="'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
// Page, part 2 --------------------------------------------------------
echo '</body>
</html>
';
// Page, part 2 --------------------------------------------------------
?>
Result
Hope this will help you. By using the PHP inbuilt SPL classes.
<?php
$file = new SplFileObject("./FL_insurance_sample.csv", "r");
$file->setFlags(SplFileObject::READ_CSV);
$file->seek($file->getSize());
$linesTotal = $file->key();
$recordsInColumn = floor($linesTotal / 4);
$res = array();
foreach ($file as $line) :
$res[] = $line;
endforeach;
$finalRecord = array_chunk($res, $recordsInColumn);
$classNames = array('column-left','column-right','column-center','column-center-right');
foreach ($finalRecord as $key => $data) : ?>
<div class="<?php echo $classNames[$key]; ?>">
<?php foreach ($data as $key1 => $row) :
if ($row[0] !== null && $row[1] !== null):
?>
<label class="checkbox" for="<?php print 'checkbox' . $row[0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $row[0]; ?>" id="<?php print 'checkbox' . $row[0]; ?>" data-toggle="checkbox">
<?php print $row[1]; ?>
</label>
<?php
endif;
endforeach; ?>
</div>
<?php endforeach;
?>

Categories