str_replace in model or the view? - php

Model
function Show_all_products()
{
return $this->db->get('printer')->result();
}
View
The table contents is being echoed in a loop
$i = -1;
echo '<ul class="products">'; foreach($products as $product) :
if($i % 11 == 10) echo '</ul><ul class="products">';
?>
<li><?php echo $product->name; ?> </li>
<?php
$i += 1;
endforeach;
echo "</ul>";
The product names are saved as Something_Something_Blah I cannot modify the product names as they are configured to show clean URL's and Breadcrumbs.
The issue is that the links in this view show as Something_Something_Blah
I tried to do a str_replace as $product = str_replace('_',' ', $product); However this isn't working.
How do i strip the '_' and insert \s ?

I see you have <?php echo $product->name; ?> which would mean $product is an object.
So you should call str_replace('_', ' ', $product->name);

<?php
$i = -1;
echo '<ul class="products">'; foreach($products as $product) :
$product->name = str_replace('_',' ', $product->name);
if($i % 11 == 10) echo '</ul><ul class="products">';
?>
<li><?php echo $product->name; ?> </li>
<?php
$i += 1;
endforeach;
echo "</ul>";
?>
str_replace must be called from within the foreach or an error will be returned. That was my mistake.

As per PHP documentation, str_replace() accepts a string or array as it's third argument. You are passing it an object. You should pass $product->name to it.
Furthermore, please strive to embed PHP in your HTML and not HTML in your PHP. You're going to find yourself echoing everything. You don't need to manually create the $i iterator either, because the foreach loop will create one for you, provided you use the foreach($x as $key => $val) syntax. You can lose the <?php echo $var;?> for <?= $var;?> too, AND concatenate with the . symbol:
<ul class="products">
<? foreach($products as $pK => $pV):?>
<? if($pK % 11 == 10):?></ul><ul class="products"><? endif;?>
<li>
<?= $pV->name;?>
</li>
<? endforeach;?>
</ul>

Related

PHP - Assign some class to li tag based on some condition inside loop

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

PHP Foreach loop if field is not empty

I am trying to master the art of the foreach loop; I have the following code which I am using with WordPress and the Advanced Custom Fields pluging. I want to turn it into a foreach loop.
<li data-thumb="<?php the_field('image_1'); ?>">
<img src="<?php the_field('image_1'); ?>" />
</li>
<li data-thumb="<?php the_field('image_2'); ?>">
<img src="<?php the_field('image_2'); ?>" />
</li>
<li data-thumb="<?php the_field('image_3'); ?>">
<img src="<?php the_field('image_3'); ?>" />
</li>
<li data-thumb="<?php the_field('image_4'); ?>">
<img src="<?php the_field('image_4'); ?>" />
</li>
<li data-thumb="<?php the_field('image_5'); ?>">
<img src="<?php the_field('image_5'); ?>" />
</li>
I have tried writing the code below but it doesn't work, and I don't know how to limit the loop to 5 (images). Note that get_field returns the image url whilst the_field returns the image.
<?php
$i=1;
foreach (!empty (get_field('property_image.$i.')) ) {
print (' <li data-thumb="<?php the_field('property_image'.$i.'); ?>">
<img src="<?php the_field('property_image'.$i.'); ?> ">
</li> ');
$i++;
}
?>
If you know that there are only 5 items, then you would just use a for or while loop. foreach is a loop designed for looping through an array of elements, which you don't have.
Consider this loop instead:
for($i = 1; $i <= 5; $i++) {
if( !empty(get_field('property_image'.$i)) ) {
echo '<li data-thumb="' . the_field('image_' . $i) . '">';
echo '<img src="' . the_field('image_' . $i) '" />';
echo '</li>';
}
}
foreach is used to iterate over arrays, e.g.
foreach (array_expression as $value) {
// current array element
}
The syntax you're using will not work with foreach (see examples to understand how it works).
For the implementation you posted, you would be better off using a normal for loop.
for ($i = 1; $i <= 5; $i++) {
// print <li>
}
To use a foreach loop, you need to have iterate over an array. get_field("name") does not return an array, however you CAN use foreach with get_fields()
$fields = get_fields();
if( $fields )
{
foreach( $fields as $field_name => $value )
{
// Output values here
}
}
Details here: http://www.advancedcustomfields.com/resources/get_fields/
In your case for loop is better as changed in the loop value is numeric. So solution will be like:
for ($i = 1; $i<=5; $i++) {
$src = the_field('image_'.$i);
printf('<li data-thumb="%s">', $src);
printf('<img src="%s" />', $src);
print('</li>');
}
If you still want to use foreach loop then you can use built-in php function range to get required numbers.
foreach (range(1, 5) as $i) {
$src = the_field('image_'.$i);
printf('<li data-thumb="%s">', $src);
printf('<img src="%s" />', $src);
print('</li>');
}
What you probably wanted to write was a while loop up there. Foreach loops don't test a condition before a cycle. Rather, foreach loops take an array and iterate over all the values within. It can also iterate over associative arrays.
<?php
$users = array(
'user_mango' => 'John Doe',
'user_2' => 'Jacob Doe',
'user_potato' => 'Jane Doe'
);
foreach ($users as $user_id => $name) {
echo $user_id, ' - ', $name, '<br>';
}
should output
user_mango - John Doe
user_2 - Jacob Doe
user_potato - Jane Doe
I'm not a wordpress developper but if you wanted to write this code in the style you started off with, here goes:
<?php
$i = 0;
while (!empty(get_field('property_image.$i.')) && $i < 5) {
echo 'YOUR TEMPLATE CODE';
$i++;
}
while loops, unlike foreach loops, test a condition before each iteration. Here in the above example code, we have our counter variable initialized to zero. Inside the loop we increase the counter variable by one on each iteration, and in the condition, we specify that in order for the full expression to be true the counter must be smaller than 5.

Output All Currency Values using PHP

I am trying to utilize the Bitcoin Charts API to display bitcoin value in all currencies as list items.
Currently I am repeating this PHP snippet in each list item:
<li class="myClass">
<?php
foreach(json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json")) as $item)
if($item->symbol == 'localbtcPLN') break;
printf("\t%s\nPLN", $item->avg);
?>
</li>
How can I simplify this so that the code is only calling the JSON file once?
Thanks for your help.
As per Vishal's assistance, I tried this:
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['ask'];//use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
?>
However, it is outputting too much data, including empty values.
Using what I've learned from Florian and Vishal, I have attempted the following snippet, which outputted the data perfectly with the caveat of some duplicated currencies.
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['avg']) != "")//check if value not empty
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['avg']; //use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
}
?>
you can run a foreach loop
<ol>
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['currency']) != "")//check if value not empty
{
?><li>
<?php echo $data['bid'];//use the keyname to get the value ?>
</li>
<?php
}
}
?>
</ol>
I think you want to show values in a certain order.
First, store the result of json_decode() in an array like #Vishal Wadhawan said.
$all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
Next, make a new array where you will store only symbol and avg:
$myvalues = array();
foreach ($all_data as $data)
{
$myvalues[$data['symbol']] = $data['avg'];
}
After that, you can use $myvalues to display avg like that:
<li class="myClass">
<?php echo $myvalues['localbtcPLN'] . ' PLN'; ?>
</li>
You can also store the 'currency' value:
$myvalues[$data['symbol']] = array(
'avg' => $data['avg'],
'currency' => $data['currency'],
);
And access it with:
<li class="myClass">
<?php echo $myvalues['localbtcPLN']['avg'] . ' ' . $myvalues['localbtcPLN']['currency']; ?>
</li>

Center Logo Inside Dynamic li Navigation

So i have a CMS which uses a foreach loop to generate the navigation which consists of individual list items inside a ul.
Basically what I want is to have my logo inserted in the center of these links, with an equal number of links on either side.
I've got my code to split up into two different columns of navigation with a gap, but I cant figure out where to place the logo div so it doesn't repeat more than once, current code also throws out some empty list items which I don't need.
<ul>
<?php $i = 0; foreach($items as $item): ?>
<li><a<?php ecco($item->isOpen(), ' class="active"') ?> href="<?php echo $item->url() ?>"><?php echo html($item->title());?></a></li>
<?php if (++$i % 3 === 0 && $i !== count($items)) echo "</li><li>"; endforeach ?>
</ul>
Thanks.
How about something like this?
UPDATE
Since your count doesn't work, try this:
<ul>
<?php
$j = 0;
$breakPoint = 0;
foreach($items as $item) {
$j++;
$breakPoint = $j;
}
$i = 0;
foreach($items as $item) { ?>
if ($i === $breakPoint) {
/* insert Logo Code */
} else { ?>
<li><a<?php ecco($item->isOpen(), ' class="active"') ?> href="<?php echo $item->url() ?>"><?php echo html($item->title());?></a></li>
<?php
}
$i++;
} ?>
</ul>
Haven't tested it. And it depends if you have a odd or even number of $item elements.

Looping Through Set Number of Posts in Wordpress, Then running same loop again on next set, etc

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>

Categories