How to only display 10 <li> items in a <ul> with php - 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.

Related

Php foreach split list into columns (preferably equally)

I have an ordered list which is 19 entries long (but could change and be more or less). I'm listing it on a drop down menu but because of its length the column is dropping below the fold of the page.
I'd like to create a separate column (ul or div) to either divide the list into 2 or 3 equally, or have set list sizes e.g. max 7 per list.
Any ideas? Current code:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$index = 0;
foreach($rs as $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
}
?>
Try something along the lines of:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$column_height = 7;
echo "<div class='column'>";
foreach($rs as $idx => $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
if($idx % $column_height) echo "</div><div class='column'>";
}
echo "</div>";
?>
and for equal split you might try this:
$max_column_height = 7;
$no_of_cols = ceil(count($rs) / $max_column_height);
$column_height = floor($count($rs) / $no_of_cols);
You should use index variable to divide it into 2 or 3 div.
Following is example to make it in three parts:
$index = 0;
foreach($rs as $v) {
if($index > 7){
$index = 0; // reset to zero. You can also seperate it by any tag div or ul if you want
}
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
$index++;
}
For an evenly spread distribution, first divide the number of elements by 7 (or whichever maximum rows you want to allow), rounding upwards. This gives the number of columns. Then divide the number of elements by the number of columns, rounding upwards: this gives you the actual number of rows you need.
I like array_chunk for this purpose:
$maxRowCount = 7;
$colCount = ceil(count($rs) / $maxRowCount);
$chunkSize = ceil(count($rs) / $colCount);
foreach(array_chunk($rs, $chunkSize) as $column) {
echo "<div class='column'>\n";
foreach($column as $v) {
echo "<a href=\"//$base_url/?action=search&colour={$v['id']}\" >{$v['name']}</a>";
}
echo "</div>\n";
}
You can create array of columns based on current index in foreach() loop like
$abc = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
$cols = [];
$perCol = 7;
foreach($abc as $index => $val) {
$colInd = $index / $perCol;
$cols[$colInd][] = $val;
}
print_r($cols);
This will split data in $abc into 3 coluns by 7 items per column.

Combination of array items with loops

I'm struggling with some loop in loop handling. I want to output one incremental item of the $additional array after each 3 items of the $items array. Also, when we arrive at item-15 in the $items array, I want to start from extra-1 again with $additional array.
$items = array(
"item-1",
"item-2",
"item-3",
"item-4",
"item-5",
"item-6",
"item-7",
"item-8",
"item-9",
"item-10",
"item-11",
"item-12",
"item-13",
"item-14",
"item-15",
);
$additional = array(
"extra-1",
"extra-2",
"extra-3",
"extra-4",
);
In the end I want to end up with something like this:
"item-1",
"item-2",
"item-3",
"extra-1",
"item-4",
"item-5",
"item-6",
"extra-2",
"item-7",
"item-8",
"item-9",
"extra-3",
"item-10",
"item-11",
"item-12",
"extra-4",
"item-13",
"item-14",
"item-15",
"extra-1"
I tried some stuff with different loops (for, foreach and while) in combination with different counters.
Any help is appreciated!
The following code does the job:
$length = count($items);
$additionalLength = count($additional);
for ($i = 1; $i <= $length; ++$i) {
echo $items[$i - 1] . "\n";
if ($i % 3 === 0) {
echo $additional[(($i / 3) - 1) % $additionalLength] . "\n";
}
}

More elegant solution to this nested loop, anyone?

I have a php procedure that scans a directory where its content is thumbnail images of pdf files. The thumbnails are then displayed in a table, and included in an iframe of a parent web page. Each thumbnail is itself a hyperlink when clicked will open the actual pdf file. To avoid having a horizontal scroll bar, 9 images in a table row is perfect. I wrote a nested loop that in effect acts like a word wrap, where it displays 9 images and then begins another row. The actual code is much more entailed, so I have it pared down to a bare minimum example. It seems almost counter intuitive on first glance, decrementing $i on the second line of the outer loop, but it works. I wonder if anyone has a more elegant solution?
$ary = array(1,2,3,4,5,6,7,8,9,10);
for ($i=1; $i<(count($ary)+1); $i++) {
$i = $i-1;
for($j=0; $j<9; $j++) {
if ($i === count($ary)) break;
echo ($ary[$i].", ");
$i+=1;
}
echo "<br>";
}
The completed code now where $ndx is the count of the array, $dir is the scanned directory containing the png images, and $rtDir is the directory where the pdf's are saved:
if ($ndx > 0) {
$tbl = '<div id="draggable" class="ui-widget-content">
<ul>
<table><tr>';
/* place 9 images on one row */
foreach ($myfiles as $index => $image) {
$pdf = basename($image, ".png");
$pdf = $pdf . ".pdf";
$pdf = $rtDir.$pdf;
$tbl .= '<td>
<span class="zoom">
<a href="'.$pdf.'" target="_blank">
<li><img id="pdfthumb'.$index.'" class="myPhotos" alt="pdf'.$index.'" src="'.$dir.$image.'" ></li>
</a>
</span>
</td>';
if ($index % 9 == 8) {
/* end the current row and start a new one */
$tbl.= "</tr></table><br><br><table style='margin-top:-40px'><tr>";
}
}
$tbl .= "</tr></table></ul></div>";
printf($tbl);
unset($myfiles);
}
Thanks everyone for your suggestions.
So you want 9 images on each row? There are usually two logical choices:
Alternative 1: You use array_chunk(), e.g. like this:
$chunks = array_chunk($images, 9);
foreach ($chunks as $chunk) {
foreach ($chunk as $image) {
// image printing goes here
}
echo '<br'>;
}
Alternative 2: You use the modulo operator, e.g. like this:
foreach ($images as $index => $image) {
// images printing goes here
if ($index % 9 == 0) { // or 8, since it's a 0-index array... I don't remember
echo '<br>';
}
}
I mostly use the second version, myself, if I have to - or I ask one of our designers to make it fit to a proper width through css. Do note also that the second version won't work if your images array is associative.
$b = count( $ary ) - 1 ;
for( $i = 0 ; $i <= $b ; $i++ ) :
echo $ary[$i] ;
if( ( $i + 1 ) % 9 == 0 ) :
echo "<br>" ;
endif ;
endfor ;
like the above comment i like modulus but i also prefer the for loop, hope this helps.

new array values on each submit 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; ?>

php adding up numbers

I think this might be an easy question for the professionals out there, but here goes.
Basically I want to get the total word count of a bunch of paragraphs. Right now I can get the word count of each paragraph, but I can't figure out how to add them all up.
$para // an array of paragraph strings
$totalcount = '';
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo $count . "<br />";
}
print_r($totalcount);
this prints a list of 41 numbers, representing the word count of each pagraphs
but the $totalcount is an array of all these numbers. How can I get the sum of all 41 paragraphs?
$totalcount = 0;
foreach(...) {
$totalcount += $count;
}
echo $totalcount;
You need to add to the total count each loop:
$para // an array of paragraph strings
$totalcount = 0;
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo "Count: ".$count . "<br />";
$totalcount += $count;
}
echo "Total Count: ".$totalcount;

Categories