PHP explode function find last child - php

I have a php plugin that explodes one line into several lines.
$graph_lines = explode( ";", $content );
$output= '';
$output .= '<ul class="lpd-bullet-list';
if($image){
$output .= ' lpd-bl-custom-icon';
}
if($style){
$output .= ' '.esc_attr($style);
}
$output .= '">';
foreach ($graph_lines as $line) {
if($line){
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= ';';
$output .= '</li>';
}
}
$output .= '</ul>';
echo $output;
After each line in the end it set ; Thats OK, but how to set . for last element? Is it possible?
Mey be i need to use end() function or another?
Help me please!

I am not very sure about your output but yes you can use end function like this:
$last_index = end(array_keys($graph_lines));
foreach ($graph_lines as $index => $line) {
if ($index == $last_index) {
// last index
} else {
// perform other tasks
}
}
Alternatively, you can use like this:
foreach ($graph_lines as $line) {
if($line){
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= ';';
if (next($graph_lines)==false) $output .= '.';//not sure where you put it.
$output .= '</li>';
}
}

You can get the number of line sizeof($graph_lines) and create a counter in your foreach.
Exemple :
$numberofline = sizeof($graph_lines);
$i=0;
foreach ($graph_lines as $line) {
if($line){
$i++;
$endofline=";";
if($i==$numberofline)
{
$endofline=".";
}
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= $endofline;
$output .= '</li>';
}
}

$content = "a;b;c;d;s;r;t;g";
$content = rtrim($content, ";");
$content = ltrim($content, ";");
$graph_lines = explode(";", $content);
$output = '';
$output .= '<ul class="lpd-bullet-list">';
$last = count($graph_lines) - 1;
$i = 0;
foreach ($graph_lines as $line) {
if ($line) {
$output .= '<li>';
$output .= $line;
$output .= ($last == $i)? '.' : ";";
$output .= '</li>';
$i++;
}
}
$output .= '</ul>';
echo $output;

You can use an shorthand IF to check if the current line is matching the last element in the array.
foreach ($graph_lines as $line) {
if($line){
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= ( $line === end ( $graph_lines ) ) ? '.' : ';';
$output .= '</li>';
}
}
An other way is to set a counter and check if the counter is equal to the count() of $graph_lines.
$counter = 1;
$total_items = count ( $graph_lines );
foreach ( $graph_lines as $line ) {
// do your stuff.
$output .= ( $counter === $total_items ) ? '.' : ';';
$counter++;
}

Count the array. and check that with the $i.
$count = count($graph_lines);
$i = 0;
foreach ($graph_lines as $line) {
if ($line) {
if ($i == $count) {
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= '.';
$output .= '</li>';
} else {
$output .= '<li>';
$output .= $image;
$output .= $line;
$output .= ';';
$output .= '</li>';
}
}
$i++;
}

Related

PHP array splice not working

I'm trying to build a shortcode in wp that displays data from 2 RSS feeds.
The problem is that I can't limit the number of items in array. I tried these solutions and none worked.
function rss_posts_func( $atts ){
$feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
$feed = array();
$feed = array_splice($feed, 0, 3);
// Loop the results
$content = '<ul class="rss-aggregator">';
foreach($feed->get_items() as $item) {
$content .= '<li class="feed-item">';
$content .= '<a href='.$item->get_permalink().'>';
$content .= $item->get_title();
$content .= '</a></li>';
}
$content .= '</ul>';
return $content;
}
Fixed with:
function rss_posts_func( $atts ){
$i = 1;
$feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
$content = '<ul class="rss-aggregator">';
foreach($feed->get_items() as $item) {
$content .= '<li class="feed-item">';
$content .= '<a href='.$item->get_permalink().'>';
$content .= $item->get_title();
$content .= '</a></li>';
if($i++ == 8) break;
}
$content .= '</ul>';
return $content;
}

How can I echo two items per one time by using PHP Foreach?

I'm using PHP to echo my products from the database. If we just use foreach, we will get the result one item per a loop, but actually I want it echo two items per one times as ub the below function.
This is my PHP function using foreach to fetch data from database.
I've used row item selector to wrap product selector, so I want to echo a block of product two times, and then it should echo the row item.
Example: row item = 1 then product = 2
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
foreach ($data as $k => $row) {
$out .= '<div class="row item">';
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
}
return $out;
}
This function will echo one item for a loop.
You can not print two times in one iteration of a loop. You can use conditional HTML output to do this job.
Consider this:
function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
$counter = 1;
$length = count($data);
if ($data) {
foreach ($data as $k => $row) {
if ($counter % 2 != 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if ($counter % 2 == 0 || $length == $counter) {
$out .= '</div>';
}
$counter++;
}
}
return $out;
}
You can use the modulus operator to make the check. If your iterator is a multiple of two it will output the appropriate elements (it does this by checking that the remainder is zero):
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
$i = 0;
foreach ($data as $k => $row) {
if( ($i % 2) === 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if( ($i + 1) % 2 === 0 || ($i + 1) === count($data) ) {
$out .= '</div>';
}
$i++;
}
}
return $out;
}
Note that the last bit ($i + 1) === count($data) is important in the event that your set holds an uneven number.

Php Array list items with different class

This is my current array that displays list items in a unordered list.
function get_bottle_colors() {
if(empty($_GET['cap_id'])) return false;
$constructor_img = get_post_meta($_GET['cap_id'], 'product_constructor_image', true);
if(is_array($constructor_img) && count($constructor_img)>0 && !empty($constructor_img[0]['title'])){
$output = '<label>Bottle Color</label><ul>';
foreach ($constructor_img as $key => $image) {
if(empty($image['image'])) continue;
$output .= '<li><a href="'.$image['image'].'" data-width="'.$img_size[0].'" data-height="'.$img_size[1].'"';
$output .= '</a></li>';
}
$output .= '</ul>';
}else{
$output = '<label>Bottle Color</label><ul></ul>';
}
echo $output;
die();
}
In total there will be up to 16 list items generated by this. I need each list item to have its own class eg: list class="red", list class="green", etc. Any idea how i go about achieving this?
Found the solution thanks to Anant. Had to declare the class array like below.
function get_bottle_colors() {
if(empty($_GET['cap_id'])) return false;
$constructor_img = get_post_meta($_GET['cap_id'], 'product_constructor_image', true);
if(is_array($constructor_img) && count($constructor_img)>0 && !empty($constructor_img[0]['title'])){
$output = '<label>Bottle Color</label><ul>';
$i = 0;
$class_array = array("a","b","c","d","e","f","g","h","i","j","k","l","n","m","n","o","p");
foreach ($constructor_img as $key => $image) {
if(empty($image['image'])) continue;
$category = 9;
$img_size = getimagesize($image['image']);
$output .= '<li class= "'.$class_array[$i].'"><a href="'.$image['image'].'" data-width="'.$img_size[0].'"
data-height="'.$img_size[1].'"';
$output .= 'data-id="'.$_GET['cap_id'].'_'.$key.'" data-part="#constructor-bottles" class="sub-caps">'.$image['title'];
$output .= '</a></li>';
$i++;
}
$output .= '</ul>';
}else{
$output = '
<label>Bottle Color</label><ul></ul>'; } echo $output; die(); }

Function to add HTML tags depending on string content

I have tried to create a function to handle text from the database to be publish with automatic formating.
If there is a \n : it should be converted to <p>...</p>
If there is a - : it should also add the list tags
My problem is that I cant really figure out how to add the <ul> and </ul> tags.
function nl2p($string){
$string = explode("\n", $string);
$paragraphs = '';
foreach ($string as $line) {
if (trim($line)) {
if (substr($line,0,1) == '-'){
$paragraphs .= '<li>' . substr($line,1) . '</li>'."\r\n";
} else {
$paragraphs .= '<p>' . $line . '</p>'."\r\n";
}
}
}
return $paragraphs;
}
Use a variable ($ul in my example):
function nl2p($string){
$string = explode("\n", $string);
$paragraphs = '';
$ul = 0;
foreach ($string as $line) {
if (trim($line)) {
if (substr($line,0,1) == '-'){
if($ul == 0){
$paragraphs .= "<ul>\r\n";
$ul = 1;
}
$paragraphs .= '<li>' . substr($line,1) . '</li>'."\r\n";
} else {
if($ul == 1){
$paragraphs .= "</ul>\r\n";
$ul = 0;
}
$paragraphs .= '<p>' . $line . '</p>'."\r\n";
}
}
}
return $paragraphs;
}
Collect all continuous <li> elements with text in a string and then enclose this string in a <ul> and </ul>.
I would search for the first character to be a dash and, if the previous line did not start with a dash, add the <ul> there. Then wrap the line in li tags and the same check at the end - if the next line does not start with a dash, then add an </ul>.
Then, as a default action, wrap the line in a paragraph.
$string = "this is a string.
New line 1.
New line 2.
- List item
- Another list item
Some more lines of text";
function nl2p($input) {
$lines = explode("\r\n",$input);
$return = '';
foreach($lines as $key => $line) {
if(strpos($line,'-') === 0) {
if(array_key_exists($key-1,$lines) AND strpos($lines[$key-1],'-') === FALSE) {
$return .= '<ul>' . "\r\n";
}
$return .= '<li>' . $line . '</li>' . "\r\n";
if(array_key_exists($key+1,$lines) AND strpos($lines[$key+1],'-') !== 0) {
$return .= '</ul>' . "\r\n";
}
continue;
}
$return .= '<p>' . $line . '</p>' . "\r\n";
}
return $return;
}
var_dump(nl2p($string));
/*
<p>this is a string.</p>
<p>New line 1.</p>
<p>New line 2.</p>
<ul>
<li>- List item</li>
<li>- Another list item</li>
</ul>
<p>Some more lines of text</p>
*/
function nl2p($input) {
if(strpos($input, "\n")) {
$slash = explode("\n",$input);
$newPara = '';
foreach($slash as $slashval) {
$slashval = '#'.$slashval;
if(strpos($slashval,"-")) {
$slashval = substr($slashval, 1);
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $hypenval) {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
$newPara .= '</ul>';
} else {
$slashval = substr($slashval, 1);
$newPara .= '<p>'.$slashval.'</p>';
}
}
return $newPara;
} else {
$slashval = $input;
if(strpos($slashval,"-")) {
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $cnt => $hypenval) {
if($cnt == 0) {
$start = $hypenval;
} else {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
}
$newPara .= '</ul>';
$newPara = $start.$newPara;
} else {
$slashval = '#'.$input;
if(strpos($slashval,"-")) {
$slashval = substr($slashval, 1);
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $hypenval) {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
$newPara .= '</ul>';
}
}
return $newPara;
}
return $input;
}

Terms by vocabulary in node.tpl

I've created a variable in template.php that let's me print terms by vocabulary. The problem is that I want to be able to pass in a vocabulary id to select a specific vocabulary. My code looks like this:
function xnalaraart_classic_print_terms($node, $vocabularies){
foreach($vocabularies as $vocabulary){
if($terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid)){
$output .= '<div>';
$output .= '<ul class="links inline">';
foreach ($terms as $term){
$output .= '<li class="taxonomy_term_' . $term->tid . '">';
$output .= l($term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description)));
$output .= '</li>';
}
$output .= '</ul>';
$output .= '</div>';
}
}
return $output;
}
and in the preprocess_node function:
$vars['terms_split'] = xnalaraart_classic_print_terms($vars['node']);
How do I write it so that I can pass in an id to $vocabularies?
I think you made this more difficult on yourself than it really is. See below for final function.
function xnalaraart_classic_print_vocab_terms($node, $vid){
if($terms = taxonomy_node_get_terms_by_vocabulary($node, $vid)){
$output .= '<div>';
$output .= '<ul class="links inline">';
foreach ($terms as $term){
$output .= '<li class="taxonomy_term_' . $term->tid . '">';
$output .= l($term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description)));
$output .= '</li>';
}
$output .= '</ul>';
$output .= '</div>';
}
return $output;
}
And then call
$vars['terms_split'] = xnalaraart_classic_print_terms($vars['node'], 10); //Where 10 is the vocab ID

Categories