I have an array like this
$products_array = array('test product', 'test new product', 'test lipsum', 'test lorem', ....);
I just got the values from array like this
echo '<ul>';
foreach( $products_array as $product_array ) {
echo '<li>$product_array</li>';
}
echo '</ul>';
But here I want something dynamic. I want to add class name according to the value set by the user. Lets say user wants to show 5 lists in a row then the markup will be like this
<ul>
<li class="first">test product</li>
<li>test new product</li>
<li>test lipsum</li>
<li>test lorem</li>
<li class="last">test update</li>
<li class="first">test new product</li>
<li>test a product</li>
<li>test new lipsum</li>
<li>test lorem</li>
<li class="last">test new update</li>
</ul>
So here you can see at last means after each 5 post its adding class last and it is adding class first to the first list and after the fifith list blocks. So in this when user will set $class = 3 then it will add last class to the third block and the first will be added to the first and the list block just after the 3rd, 6th, 9th etc
I have done like this
$last = '4' //set 4. so for 4th,8th,12th it will add class last. and for 1st, 5th, 9th it will add class first
echo '<ul>';
$i = 0;
$count = count($products_array);
foreach( $products_array as $product_array ) {
$i++;
$class = '';
if( $i == $count ) {
$class = 'last';
}
echo '<li class='.$class.'>$product_array</li>';
}
echo '</ul>';
But its not working. So can somone tell me how to do this? Any help and suggestions will be really appreciable. Thanks
Use a modulus to determine the class to add. The logic goes...
When the remainder is 0, we are on the last item of each group (the nth of n)
When the remainder is 1, we are on the first item of each group (the 1st of n)
Otherwise, we are somewhere in the middle
For example
$last = 4;
?>
<ul>
<?php
foreach ($products_array as $index => $product) :
switch(($index + 1) % $last) { // array indexes are 0-based so add 1
case 0 :
$class = 'last';
break;
case 1 :
$class = 'first';
break;
default :
$class = '';
}
?>
<li class="<?= $class ?>"><?= htmlspecialchars($product) ?></li>
<?php endforeach ?>
</ul>
eval.in demo
This should do the trick. You could also use modulus, but i am not quite sure how it behaves with small perPage-settings.
//your perPage-setting, change this for more elements per page
$perPage = 3;
$count = count($products_array);
//loop over elements
for($i = 1; $i <= $count; $i++) {
$className = "";
if($i / $perPage == 0) {
$className = "last";
} else if((floor($i / $perPage) * $perPage + 1 == $i)
$className = "first";
echo '<li class='.$className.'>'.$product_array[$i-1].'</li>';
}
Related
I have following Two-dimensional array:
$data = array
(
array("1.2"),
array("2.5"),
array("4.7"),
array("5.7"),
array("3.5"),
array("7.2"),
array("4.7"),
array("3.5")
);
Now I am displaying my records through loop:
<ul>
<?php
for($i=0; $i<count($data); $i++):
?>
<li><?php echo $data[$i][0]; ?></li>
<?php
endfor;
?>
</ul>
and this is the result:
Now I want to check some condition inside loop and add class="red" to li.
Example 1:
If 4.7 found inside the loop, add class="red" to next all li tags.
Example 2:
If 3.5 found inside the loop, add class="red" to next all li tags.
Example 3:
If 5.7 found inside the loop, add class="red" to next all li tags.
Any idea how to add class to li tags when some condition match.
Thanks.
You can just switch on the class as soon as a matching item is found.
$switch_value = '4.7'; // set the value where you want to switch colors
$class = ''; // initialize the class to empty string
foreach ($data as $value) {
echo "<li$class>$value[0]</li>";
// set the class to red the first time the value is found
if ($value[0] == $switch_value) $class = ' class="red"';
}
It's important to set the class after echoing the list item to get the output you want.
You can do it this way:
<ul>
<?php
$class = ''; $num = 4.7;
for($i=0; $i<count($data); $i++):
?>
<li class='<?php echo $class; ?>'><?php echo $data[$i][0]; ?></li>
<?php
if( $data[$i][0] == $num ) $class = 'red';
endfor;
?>
</ul>
Just change the $num to desired value programmatically.
Edit: move the if block to end of for block to leave the number's occurrence.
Just check a condition with a value, and assign it
<ul>
<?php
$isRed = false;
$value_to_search = 3.5;
for($i=0; $i<count($data); $i++):
?>
<li class="<?php echo ($isRed == true)?'redClass':'';"><?php echo $data[$i][0]; ?></li>
<?php
if($data[$i][0] == $value_to_search )
$isRed = true;
endfor;
?>
</ul>
I guess you can use something like:
<ul>
<?php
$red = false;
for($i=0; $i<count($data); $i++){
if($data[$i][0] == "3.5" or $data[$i][0] == "4.7" or $data[$i][0] == "5.7" or $red){
echo "<li class=\"red\">{$data[$i][0]}</li>";
$red = true;
}else{
echo "<li>{$data[$i][0]}</li>";
}
}
?>
</ul>
Output:
<ul><li>1.2</li><li>2.5</li><li class="red">4.7</li><li class="red">5.7</li><li class="red">3.5</li><li class="red">7.2</li><li class="red">4.7</li><li class="red">3.5</li></ul>
Ideone Demo
http://ideone.com/s2gdmG
Right now i am working around one PHP script based on http://simplehtmldom.sourceforge.net/.
Here is my code:
<?PHP
foreach ($html->find('li.tooltip') as $ul) {
$id = $ul->id;
$dt = "data-text";
$dt = "data-text";
$cid = "colvar-id";
$datatext = $ul->$dt;
$colvarid = $ul->$cid;
$countN = count($id);
$number = 1;
$N = $i++;
if ($N == "") {
$N = 0;
}
}
?>
<?PHP echo "Result is: $countN"; ?>
This code is suposed to count the number of founded occurencies, but it displays nothing.
All i want is to count the founded occurencies and simply display the number of occurencies.
Thanks in advance!
You can use count():
$html = str_get_html(<<<EOF
<ul>
<li>not a tooltip</li>
<li class="tooltip">tooltip</li>
<li class="tooltip">also a tooltip</li>
</ul>
EOF
);
echo count($html->find('li.tooltip'));
// 2
I have a list of returned subcategories. I only have access to the template display and not to the MySQL query so no, I can't limit the query.
Right now all the results are returned. I would like to limit the list to 5, and then add a "more" link if there are more than 5 results.
I know I did this wrong because I don't think count is actually tied to the foreach:
<ul class="sub-categories">
<?php
while (count($category->getChildren()) <= 5) { // line I added for while loop
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount())
continue;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
} // line I added for while loop
?>
</ul>
Keep track within the foreach and break; when you've reached the limit:
<ul class="sub-categories">
<?php
$i = 0;
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount()) continue;
$i++; if($i>5) break;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
?>
</ul>
I have a loop that displays <li>'s and I need to add a class to the 1st and then every six <li>'s
Example:
while ($db_field = mysql_fetch_assoc($result)) {
<li (if mod of 6 add class="something")>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li class="something">Six</li>
<li>Seven</li>
}
...
It's quite easy using the modulus % operator:
$counter = 0;
while ($r = mysql_fetch_assoc($res) {
$isSixthsLi = (bool) (($counter++) % 6 == 0);
echo $isSixthsLi ? '<li class="something">' : '<li>';
echo htmlentities($r['content']);
echo '</li>';
}
The ($counter++) % 6 expression means the remainder of $counter divided by 6, then increment $counter. If the remainder is zero (and this is true for 0, 6, 12, ...), then you print the <li> with a class name, else you did not.
i think this list is coming dynamically then you can use
<?php
$i=0;
foreach ($in as $v){
$i++;
$class = (!$i%6) ? "something : ""; ?>
<li class="<?=$class?>"><?=$v?></li>
<?php } ?>
Note : i have use shorthand tag <?= , you can use <?php echo instead
I have looked and looked and tried to find an answer for what I've been looking for, but I have yet to see an answer for this:
I am trying to generate a Wordpress loop that takes all the posts from a single category and displays them three at a time inside <li></li> tags.
Output should look like this:
<li>My post title | Another Title | Third title</li>
<li>The next post title | A different post | Post #6</li>
<li>And so on | And so forth</li>
I need this to loop through all the entries in the category until finished, and then exit the loop.
My code is completely non-working at this point, but I've provided what I'm working with below. If anyone has any solution to this, I'd love to give mad props to you, as this has hounded me for three days without any solution so far.
<?php // Loop through posts three at a time
$recoffsetinit = '0';
$recoffset = '3';
query_posts('cat=1&showposts=0');
$post = get_posts('category=1&numberposts=3&offset='.$recoffsetinit.');
while (have_posts()) : the_post();
?>
<li>
<?php
$postslist = get_posts('cat=1&order=ASC&orderby=title');
foreach ($postslist as $post) : setup_postdata($post);
static $count = 0; if ($count == "3") { break; } else { ?>
<?php $count++; } ?>
<?php endforeach; ?>
<?php $recoffsetinit = $recoffset + $recoffsetinit; ?>
</li>
<?php endwhile; ?>
I hacked up your solution to make it work. It took a little doing, since my code-fu is not what you'd call "good." Here's the solution:
<ul>
<?php
query_posts('category=1&showposts=0');
$posts = get_posts('category_name=my_cat&order=ASC&orderby=title&numberposts=0');
$postsPerLine = 3;
$currentPostNumber = 0;
foreach ($posts as $post) :
if ($currentPostNumber == 0) {
echo '<li>';
}
?>
<?php
$currentPostNumber++;
if ($currentPostNumber >= $postsPerLine) {
$currentPostNumber = 0;
echo '</li>';
}
endforeach;
?>
</ul>
Thanks for the input!
No wordpress to test with, and no time, but something like this might be a better way of going about it?
<?php
$postList = get_posts('cat=1&order=ASC&orderby=title');
$postsPerLine = 3;
echo "<ul>";
echo buildPosts($postList, $postsPerLine);
echo "</ul>";
function buildPosts($list, $perLine) {
$out = '';
$currentPostNumber = 0;
foreach ($list as $post) {
if ($currentPostNumber == 0) {
$out .= '<li>';
}
$out .= "<a href='" . the_permalink() . "'></a> ";
$currentPostNumber++;
if ($currentPostNumber <= $perLine) {
$currentPostNumber = 0;
$out .= '</li>';
}
}
return $out;
}
?>
Just snag all the posts for a category, at once, then iterate over it. Create a link to every post, toss in the separator, and on every third post start a new <li>
<ul>
<?php
global $post;
$postsPerLine = 3;
$counter = 0;
$myposts = get_posts('category=1&orderby=title&order=ASC');
foreach($myposts as $post) :
echo (++$counter % postsPerLine) ? : '<li>';
?>
<?php the_title(); ?></li>
<?php
echo ($counter % postsPerLine) ? ' | ' : '</li>';
endforeach;
?>
</ul>