new array values on each submit php - php

Dont know much PHP and wonder how I can get the new values from an array each time I submit, I have a form with 5 fields, the form sends the information to a txt-file then I want to take only the two first items each time the form submits and display it in a list item, but cant seem to figure out how the loop should work? any tips please?
For now I have this and it successfully prints out the fist textblock in the txt-file, but when I submit the form again nothing happens, what is wrong?
$myFile = 'demo.txt';
$content = file_get_contents('demo.txt');
$content_array = explode(";", $content);
<div id="info_php">
<ul id="list_php">
<?php for($i=count($content_array); $i < 1; $i--);
echo '<li>'; echo $content_array[0]; echo'</li>';?>
</ul>
</div>

You have an error in syntax, the for loop is terminated by semicolon, and you are printing only the first element as $content_array[0], instead of using the loop variable. Try this:
<?php
for($i=count($content_array); $i < 1; $i--) {
echo '<li>'; echo $content_array[$i]; echo'</li>';
}
?>

The first thing you need to do is change your loop like this:
<?php
$count = count($content_array); // total rows
$limit = $count > 2 ? $count - 2 : 0; // at most we want two rows
for ($i = $count; $i > limit; $i--) {
echo '<li>' . $content_array[$i - 1] . '</li>';
}
?>
This will get the last two rows of the txt file

This is it!
<?php
$myFile = 'demo.txt';
$content = file_get_contents($myFile);
$content_array2 = explode("\n", $content);
?>
<?php for($i = 0; $i < count($content_array2); $i++):
$values = explode(';', $content_array2[$i]);?>
<li><?php echo $values[0].$values[1]; ?></li>
<?php endfor; ?>

Related

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 ?

How to only display 10 <li> items in a <ul> with php

I have a problem using tcpdf. A form on my page sends a post variable containing content with <li></li> items.
$fzg_features = '<li>' . $_POST['fzg-features'] . '</li>';
I was able to count all <li> items but i only want to display item 1-10.
Is it possible to index the <li> items with php and manage the output? e.g. 4-6 of all list items?
The problem is the source of $_POST['fzg-features']. It comes from a wp plugin writing the whole content as <li></li> items in an array key as a single string.
When it comes as single string you can explode </li> and then remove <li>.
$pizza = "<li>example</li><li>another example</li>"; // Example string
$pieces = explode("</li>", $pizza); // Make many small pieces
foreach ($pieces as $key => $piece) { // Go through all pieces
if ($key === 9) break; // First key in array is 0, so we limit it to 9.
echo substr($piece, 2); // Remove first 2 characters
}
Great, I stand in your debt. Works fine for me. My main issue was to calculate columns for displaying Car features in tcpdf as a 3 column list. As it is not possible using css this solution worked for me:
$fzg_features = $_POST['fzg-features'];
// $pieces holds the array
$pieces = explode("</li><li>", $fzg_features); // Make many small pieces
foreach ($pieces as $key => $piece) { // Go through all pieces
}
// column calculation
$columns = 3;
$colamount = count($pieces) / $columns;
$colamount1 = ceil($colamount);
$colamount2 = ceil($colamount)*2;
// first column
for ($i = 0; $i <= $colamount1 -1; $i++){
echo '<li>' . $pieces[$i] . '</li>';
};
echo '<br><br>';
// second column
for ($i = $colamount1; $i <= $colamount2 -1; $i++){
echo '<li>' . $pieces[$i] . '</li>';
};
echo '<br><br>';
// third column
for($i = $colamount2; $i <= count($pieces)-1; $i++){
echo '<li>' . $pieces[$i] . '</li>';
};
Thanks a lot for your help.

PHP Array Looping & Exploding

I'm not very experienced in using PHP, but I'm having a hard time thinking of a way to do this. I'm reading from a file and exploding on ":" as you can see here.
<?php
$datainfo = file('data.txt');
for($i = 0; $i < count($datainfo); $i++){
$expdata = explode(':', $datainfo[$i]);
}
?>
The issue is that I need to reference specific indexes of the resulted explosion like this.
<p> <?php echo $expdata[1] ?> </p>
I'm getting back an array of the last line inside the data.txt file. I know why It's happening, I just don't know how to get what I want here. (Sorry Very New). Data.txt contain the following.
name:Octopod Juice Stand
balance:20
price:0.5
customers:12
starting:2014-05-26
end: 2014-09-01
juice:15.25
fruit:10
Change your code to
<?php
$datainfo = file('data.txt');
$expdata = array();
for($i = 0; $i < count($datainfo); $i++){
$expdata[] = explode(':', $datainfo[$i]);
}
?>
And then to get the first label.
<p><?php echo $expdata[0][0]; ?></p>
Or the first value
<p><?php echo $expdata[0][1]; ?></p>

Insert line break after every two rows of database

I have a little script that prints a certain amount of rows in a mysql database.
Is there any way to make it so that after every second row it prints, there is a line break inserted?
Adding a line break after every row is simple, but I don't know how to add one after every other row. Is that possible?
You write "script" but in tags you have PHP, so I suppose you need PHP code:
foreach ($rows as $row) {
if ($i++ % 2) {
// this code will only run for every even row
}
...
}
$i=1;
while ($row = mysql_fetch_array($query))
{
//your code
if ($i % 2 == 0)
echo '<br>';
$i++;
}
add new variable before the loop
$i = 0;
then in your loop add
if ($i != 0 && $i%2 == 0)
echo '<br/>';
Depending on the language, something like this should do it: (in php) (where $arr is an array of results)
$str = '';
$i = 0;
for ($i=0; $i<count( $arr ); $i++)
{
if ( ( $i + 1 ) % 2 === 0 )
{
$str .= $arr[$i] . '<br />';
}
else
{
$str .= $arr[$i];
}
}
echo $str;
Use php and modulo.
such as
if($i % 3)
{
echo '<br />'..
If you need to do this inside the query for some reason, you could use something like
SELECT
<your fields>,
IF (((#rn:=#rn+1) % 3)=0,'<br>','') as brornot
FROM
<your tables and joins>,
(#rn:=0)

PHP - Tricky... array into columns, but in a specific order

<?php
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$i = 0;
foreach ($combinedArray as $r ){
/*** use modulo to check if the row should end ***/
echo $i++%$num_cols==0 ? '<div style="clear:both;"></div>' : '';
/*** output the array item ***/
?>
<div style="float:left; width:33%;">
<?php
echo $r;
?>
</div>
<?php
}
?>
<div style="clear:both;"></div>
The above code will print out the array like this:
apple --- banana --- watermelon
lemon --- orange --- mango
However, I need it like this:
apple --- watermelon --- orange
banana --- lemon --- mango
Do you know how to convert this? Basically, each value in the array needs to be placed underneath the one above, but it must be based on this same structure of 3 columns, and also an equal amount of fruits per column/row (unless there was like 7 fruits there would be 3 in one column and 2 in the other columns.
Sorry I know it's confusing lol
Thanks everyone for your help... I realized a better way to do it though. Simple put, I have 3 columns floating next to eachother. And in each column, I add a list of the items into it and stop when I hit the max items per row.
working code:
<div style="float:left; width:33%;">
<?php
$combinedArraySizeOf = sizeof($combinedArray);
$num_cols = 3;
$iPerRow = $combinedArraySizeOf / $num_cols;
for ($i=0; $i!=$combinedArraySizeOf; $i++){
if ($i % $iPerRow == 0){
echo '</div><div style="float:left; width:33%;">';
}
echo $combinedArray[$i]."<br />";
}
?>
</div>
<div style='clear:both;'></div>
Don't forget to clear both at the end if necessary :P
Why aren't you doing exactly what you want to do? I mean show them in columns, instead of rows?
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rowCount = ceil(count($combinedArray)/$num_cols);
$i = 1; // in order the modulus to work correctly
?>
<div style="float: left; width:33%"> <!-- this is the first column -->
foreach ($combinedArray as $r ){
?>
<div> <!-- just a div containing $r -->
<?php
echo $r;
?>
</div>
<?php
// this is where the magic happens
// check if we have enough rows and start another column
if ($i % $rowCount == 0) {
?>
</div> <!-- close the previous column and start a new one -->
<div style="float: left; width:33%"> <!-- this is the new column -->
<?php
}
$i++;
}
?>
</div> <!-- closing the last open column -->
<div style="clear:both;"></div>
This should do just the job you wish. Marvin's answer is better if you want to use only tables without divs.
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$step = 2;
$i = 0;
$new_array = array();
foreach ($combinedArray as $r ){
$remainder = ($i % $step);
$new_array[$remainder][] = $r;
$i++;
}
foreach($new_array as $array)
{
echo implode(' --- ', $array)."<br>";
}
Would this work?
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rows = ceil(count($combinedArray)/$num_cols);
for($i = 0; $i < $rows; $i++){
for($j = 0; $j < $num_cols; $j++){
echo $combinedArray[(($i+$j) * $rows)-$i];
}
echo "<br />";
}
This would also need to check that the value existed for cases where the number of items wasn't precisely divisible by the number of columns, you could do that with the following change:
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rows = ceil(count($combinedArray)/$num_cols);
for($i = 0; $i < $rows; $i++){
for($j = 0; $j < $num_cols; $j++){
$cell = (($i+$j) * $rows)-$i;
if($cell > count($combinedArray)) break;
echo $combinedArray[$cell];
}
echo "<br />";
}
If this order is what you ideally want, but it's not critical that it works in all browsers, perhaps you should look at coloumn layout (still very experimental css3 draft). If you use dispay inline block for the element in each coloumn you'll have the current order as a fallback.
You could also use a table for the layout and use a for loop something like this (pseudo php code, it's been a while since I've coded any php):
maxHeight = Math.ceil(array.length / 3) // meaning length=6 will give 3,
// length=7 will give 4
$x = -1; // horizontal index
for(i = 0; i < array.length(); i++){
$y = i % maxHeight; // vertical index
if($y == 0){
$x++;
}
addToTable($x,$y, array[i]);
}

Categories