Explode and foreach to create multi <td> table - php

I'm using explode() to basically take apart paragraphs into individual words. Works great. The looping through with a foreach(). Also works great. Nothing complicated here.
$title_pieces = explode(" ", $title_fixed);
foreach($title_pieces as $tpiece){
echo "<b>$tpiece<br>";
}
Unfortunately this returns just an ugly long list of words. What I'd like to do but can't quite figure out how is to put this all in a nice table. Creating the table is no problem, the part I can't figure out is how to get it to write more than one $tpiece per row. I'd like to have maybe 5 <td>s in each row.
So if I do:
foreach($title_pieces as $tpiece){
echo "<tr><td>$tpiece</td></tr>";
}
I'm still just left with a long list. Can someone point me in the right direction here.

Just a sample-code. Work around with the modulo-operator.
<?php
$i = 1;
echo '<table><tr>';
foreach($title_pieces as $tpiece){
if ($i % 10 == 0)
echo "</tr><tr>";
echo "<td>$tpiece</td>";
$i++;
}
echo '</tr></table>';
?>

Try something like:
$count = 1;
echo "<tr>";
foreach($title_pieces as $tpiece){
if ($count % NUM_COLS == 0)
echo "</tr><tr>";
echo "<td>$tpiece</td>";
$count++;
}
echo "</tr>";
There's probably a clever optimization in there. What you are doing is counting the number of cells and starting a new row when the count divides NUM_COLS evenly. It's important count starts on 1, not 0, or you'll have an empty row.

Related

How to display the serial number of the table rows in descending order in php?

I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.
Code sample:
$i= 0;
while(condition)
{
$i++;
echo "<td>".$i."</td>";
}
Output:
I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.
example:
#
10
9
8
7
6
5
4
3
2
1
Any help is highly appreciated.
If you already have loop outputting the 1-10 version, you could simple change the output to show 11 minus the current count...
echo "<td>".(11-$i)."</td>";
Or to change the whole code, you could start at 11 and decrement the counter each time and output it that way
$i= 11;
while($i>0)
{
$i--;
echo "<td>".$i."</td>";
}
count first and after do a loop in reverse order
$i= 0;
while(condition)
{
$i++;
}
for ( cnt= $i, $i>= 0, $i--){
echo "<td>".$cnt."</td>";
}
If you are fetching from MYSQL Database and you're using PDO to connect to Database
//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows
while(){
$sn--;
echo '<td>' . $sn . '</td>';
}
So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop.
I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...

How to split a PHP loop in 2 parts?

I have a weather json from where I get a wether forecast for 8 days. My problem is that I want to show the result in a table of 2 rows of 4 days each.
I managed to do it but in a very odd way that was pure begginer's luck during a trial-error-trial attempt :-) I don't even understand quite well why it is splitting the result in 2 rows... but it works!!! The only thing I could not do was to include a "hr" line between the 2 rows, to make the table easier to read.
You can see the result here http://www.meteocaldas.com/previsao_ds.php
With current code I am displaying each day forecasted values inside the same "td" in different lines using "br". I have been reading that it is not correct to use "br" inside "td" so I am not sure that I am doing the righ thing. Wouldn't it be better to use a table with 4 columns (one for each day) and have different rows for each of the values?
Is there any way to rewrite this code to make it more efficient and look less "childish"? :-) Thanks in advance!
<?php
(...)
$decoded = json_decode($rawData, true);
?>
<table>
<?php for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime = $dailyvalue['time'];
$dailyIcon = $dailyvalue['icon'];
$dailyTempMax = round($dailyvalue['temperatureMax'],0);
$dailyTempMin = round($dailyvalue['temperatureMin'],0);
(...)
?>
<!-- table for 8 day's forecast (2 rows/4 days each) -->
<td>
<?php echo strftime("%a %d",$dailyTime) ?>
<br>
<?php echo '<img src="path/'.$dailyIcon.'.png">' ?>
<br>
<?php echo $dailyTempMin.'º' ?> </span>
<br>
<?php echo $dailyTempMax.'º' ?></span>
<br>
(...)
<?php if ($k == 3) {
echo '</td></tr>';
} ?>
<?php
}
?>
</td></tr><table>
As per your comment-request, here's some sample-pseudo code, based on your code above:
<?php
(...)
$decoded = json_decode($rawData, true);
for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime[$k] = $dailyvalue['time'];
$dailyIcon[$k] = $dailyvalue['icon'];
$dailyTempMax[$k] = round($dailyvalue['temperatureMax'],0);
$dailyTempMin[$k] = round($dailyvalue['temperatureMin'],0);
}
?>
<table>
<?php
echo "<tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".strftime("%a %d",$dailyTime[$k])."</td>"; // this will make the "datetime" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td><img src=path/".$dailyIcon[$k].".png></td>"; // this will make the "icon" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMin[$k]."º</td>"; // this will make the "MinTemp" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMax[$k]."º</td>"; // this will make the "MaxTemp" row
}
echo "</tr>";
// put stuff you want between the tables here
echo "<tr>";
for($k = 4; $k <= 7; $k++){
// proceed to do the same as above
Mind you, there are further ways you can reduce the screen clutter (like moving the table-drawing for loops into a function), but this is the general gist of it
Why don't you simply stack two different table on each other ?

Remove the 0 from for results

Currently, I'm messing around with SoundCloud's API and it's returning something that looks like this.
0. HotBox Michael da Vinci Prod Free P.mp3
https://api.soundcloud.com/tracks/373337717/stream?client_id=OURID
1. LSSR Chris P Prod Jake Knight.mp3
https://api.soundcloud.com/tracks/373336760/stream?client_id=OURID
Which is working properly as how the code appears, here it is how I'm printing out the results (very messy but I'm just messing around)
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
print '<br>'; print '<br>';
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
print ''.$i.'. '.$title.'.mp3';
print '<br>';
print $stream = ''.$b2.'?client_id=OURID';
}
Now what I'm wondering is how under every circumstance can we make the 0. return as a 1. and continue counting upwards until reaching the end of the for loop, not removing the 0. data but only changing the number.
I recommend a foreach loop with the $i counter declared in the loop and just increment it as you go.
Untested code:
foreach ($house as $i=>$row){
echo '<br><br>',++$i,'. ',preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title'])),".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
p.s. I've improved the regex pattern and eliminated all single-use variable declarations. You can break this up over many lines if you prefer.
If you want to avoid the first iteration's double break tags...
foreach ($house as $i=>$row){
if($i) echo '<br><br>'; // if $i is not 0
echo ++$i,'. ';
echo preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title']));
echo ".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
Based on the comments and your description of what you are trying to do, it sounds like you just need to add another iteration variable:
# Add another variable
$a = 1;
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
echo '<br><br>';
# Here you have the $a show up starting at 1
echo ''.$a.'. '.$title.'.mp3<br>';
echo $stream = ''.$b2.'?client_id=OURID';
# Auto increment here
$a++;
}

How can I make a PHP counter?

I know I have done this in Javascript once, but how can I make it in PHP?
Basically I want to do this:
if (empty($counter)){
$counter = 1;
}else{
"plus one to $counter" ($counter++?)
}
But it didn't work when I tried. How would I go about doing this?
Thank you :)
EDIT: This is so I can do:
if ($counter == 10){
echo("Counter is 10!");
}
EDIT:
This is all in a "while()" so that I can count how many times it goes on, because LIMIT will not work for the query I'm currently doing.
why the extra if into the while?
i would do this:
$counter = 0;
while(...)
{
(...)
$counter++;
}
echo $counter;
To increment a given value, attach the increment operator ++ to your integer variable and place it within your while loop directly, without using a conditional expression to check if the variable is set or not.
$counter = 1;
while(...){
echo "plus one to $counter";
$counter++;
}
If your counter is used to determine how many times your code is to be executed then you can place the condtion within your while() expression:
while($counter < 10){
echo "plus one to $counter";
$counter++;
}
echo("Counter is $counter!"); // Outputs: Counter is 10!
You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.
if (empty($counter)){
$counter = 1;
}else{
echo 'plus one to $counter';
$counter++;
}
Something along those lines will work for you.
PHP is pretty flexible with what you throw at it. Just remember, statements need a semicolon at the end, and if you want to output to the screen, (in the beginning) you'll be relying on echo statements.
Also, when dealing with echo statements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:
$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter

Dynamic Table Layout using PHP Logic

I have simple table that has about 80 rows, which I populate dynamically using PHP. What I am trying to do is to layout those rows in chunks for each column. So if I have 80 rows, I would like 4 columns of 20 rows or so, maybe the last column has less or more depending on the total number of rows. The total number of rows can change!
I am having trouble coming up with an implementation method that will not get messy! Anyone know of a simple way that I can implement this.
I have tried using a counter as I loop the data to populate the table and when a multiple of of 20 is reached move to the next block but that didn't work for me as I had extra rows left over.
foreach($indexes as $index){
$counter++;
echo '<tr>';
if($counter > 20){
$multiplier = $counter / 20;
$head = '<td></td>';
for($i=1; $i<$multiplier; $i++){
$head .= '<td></td>';
}
}
if($counter < 20){
$head = '';
}
echo "$head<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";
echo '</tr>';
}
Thanks all for any help
I would do :
$nbCols = 4;
$nbRows = count($indexes)/$nbCols;
for($row=0; $row<$nbRows; $row++) {
echo "<tr>";
for($i=0; $i<$nbCols; $i++) {
$index = $indexes[$row + ($i*$nbRows)];
echo "<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";
}
echo "</tr>";
}
Wouldn't you want to see the remainder of your division and deal with that also?
if($counter % 20 == 0){
// You've no remainder
}else{
// Do another loop to output the odd rows
}
Or you could % 2 == 0 to see if it's even, and then just multiply the whole result by 10.
Be sure to look at ceil() and floor() also for ensuring your number of rows is a round number.
if you dont mind to have this kind of cell order:
1 2 3 4
5 6 7 8
you can use <div style='float:left'>$cellValue</div> in the loop without use of table.

Categories