If else statement to identify the last term in the array - php

I have the below code to list the Array of terms, I am placing a comma between the terms if there are more than one term assigned to the post.
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$count = count($terms);
$i = 0;
$term_list = '<span>';
foreach ($terms as $term) {
$i++;
$term_list .= '#<span>' . $term->name . '</span>';
if ($count != $i) {
$term_list .= ', ';
} else {
$term_list .= '</span>';
}
}
}
Now, I would like place a & between the last two terms instead of a , if there are more than one term assigned to the post.

I think it is easier to solve it with an array.
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$term_array = [];
foreach ($terms as $term) {
$term_array[] = '#<span>' . $term->name . '</span>';
}
if(count($term_array) > 1){
$last = array_pop($term_array);
$term_list = '<span>' . implode(', ', $term_array) . '</span>';
$term_list .= ' & ' . $last;
} else {
$term_list = '<span>' . $term_array[0] . '</span>';
}
}
OR:
$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
$count = count($terms);
$i = 1;
$term_list = '<span>';
foreach ($terms as $term) {
$term_list .= '#<span>' . $term->name . '</span>';
if($i !== $count){
if($i === $count - 1){
$term_list .= ' & ';
} else {
$term_list .= ', ';
}
}
$i++;
}
$term_list .= '</span>';
}

Check if $count is equal to $i + 1:
if ($count != $i) {
if ($count == $i + 1)
$term_list .= '& ';
else
$term_list .= ', ';
} else {
$term_list .= '</span>';
}
That should do it.

You could check if the $count is equal to $i.
$i = 1;
if ($count != $i) {
$term_list .= ', ';
} else if ($count == $i) {
$term_list .= '& ';
} else {
$term_list .= '</span>';
}

Find the last element of the array, then just check each item within your loop against lastelement, then do your 'magic' ;).
Example:
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'Now you know that $v is the last element, do something';
}
}

Related

How to remove the last comma of a Wordpress php foreach output?

I already tried some things with trim and so on but nothing works.
Maybe I made a mistake and you can help me? The code looks currently like that:
$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
$output = '';
foreach ($terms as $term) {
$output .= '' . $term->name . ', ';
}
};
echo $output;
Try putting in substr_replace($term->name,"",-1), check documentation for more info, this should delete comma from last string.
just add a counter to check the last item of the array
$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
$output = '';
$i = 0;
foreach ($terms as $term) {
$output .= '' . $term->name . ' ';
$output .= ($i == count($terms) - 1) ? '' : ',';
$i++;
}
};
echo $output;

Proper way to pass an array

This one is boggling me, because I think the code is right but something just isn't clicking, this is a code I picked up from Yanick Rochon and it works when the array is hard coded (in the commented out area) but when I push together the array from all of the pa_mymelp terms it doesn't behave as expected, it uses the entire line as an item vs multiple items per line, and does not create children either, wonder why.. thank you!:
<?php
$thearray = array();
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories = $term->name;
array_push($thearray, $categories);
}
$categoryLines = $thearray;
/*$categoryLines = array(
"Dodge>2002>Ram 3500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler",
"Dodge>2001>Ram 2500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler"
);*/
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '>');
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '>', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$str .= '<li title="' . $currentPath . '">' . $node .
displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
'</li>';
}
$str .= '</ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "test", '>');
?>

PHP explode function find last child

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++;
}

Adding products to Magento menu

Today I am trying to add products like this:
– Category
– – SubCategory1
– – – Product 1
– – – Product 2
– – – Product 3
– – SubCategory2
– – – Product 1
– – – Product 2
– – – Product 3
My current magento version is ver. 1.9.0.1
I was searching about it on the internet I found this code but its giving me syntax error not sure why. Please check but this code tested on Magento ver 1.4 I am not sure if it will work for me or not.
protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
$isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
{
if (!$category->getIsActive()) {
return '';
}
$html = array();
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array)$category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = ($children && $childrenCount);
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="'.$outermostItemClass.'"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$htmlLi = '<li'; foreach="" ($attributes="" as="" $attrname=""> $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . '"';
}
$htmlLi .= '>';
$html[] = $htmlLi;
$html[] = '<a href="'.$this->getCategoryUrl($category).'" '.$linkclass.'="">';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
// Grabbing the products for the category if it's level is 1
if ($level == 1) {
$catId = $category->getId();
$categorie = new Mage_Catalog_Model_Category();
$categorie->load($catId); // this is category id
$collection = $categorie->getProductCollection()->addAttributeToSort('name', 'asc');
$html[] = '<ul>';
foreach ($collection as $pc)
{
$p = new Mage_Catalog_Model_Product();
$p->load($pc->getId());
$data = $p->_data;
$html[] = '<li>'.$data['name'] .'</li>';
}
$html[] = "</ul>\n";
}
// Done
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
($j == $activeChildrenCount - 1),
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '';
$html = implode("\n", $html);
return $html;
}
</li';>
Its giving syntax error on line:
$htmlLi = '<li'; foreach="" ($attributes="" as="" $attrname=""> $attrValue) {
and at the end of code:
</li';>

Wrapping foreach result in a div

I have this function working great
<?php
$categories = get_categories(array(
'hide_empty' => 0,
'taxonomy' => 'category',
'orderby' => 'title',
'order' => 'ASC'
));
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
$postlist .= "<b><a name='$firstletter'> $firstletter </a></b><br>\n";
$nav .= "<a href='#$firstletter'> $firstletter </a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>\n";
}
print $nav . "<br>" . $postlist;
?>
What I need, is to wrap the entire list starting with the letter. For example, Letter M will be wrapped in a div with all the categories starting with M.
This is what I currently get: http://i.imgur.com/PEmJw03.png - Any help would be appreciated, thank you.
You seem to be on the right path. I think this is what you are requesting to do:
$closeLastDiv = false;
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
if ($firstletter == ""){ //first time through
$postlist .= "<div>";
$closeLastDiv = true;
} else {
$postlist .= "</div><div>";
}
$postlist .= "<b><a name='$firstletter'> $firstletter </a></b><br>\n";
$nav .= "<a href='#$firstletter'> $firstletter </a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>\n";
}
if ($closeLastDiv) {
$postlist .= "</div>";
}
All you need is comparte the current letter with before letter, and if changed print the starting wrapper + content. When the letter changes, close the wrapper and open the next wraper.
Something like this:
$current = "-";
$postlist .= "<div>";
foreach ($categories as $category) {
$firstletter = strtoupper(substr($category->name,0,1));
$link = get_category_link( $category->term_id );
if ($firstletter != $current) {
$postlist .= "</div><div id='{$firstletter}'>";
$postlist .= "<b><a name='{$firstletter}'>".$firstletter."</a></b><br>\n";
$nav .= "<a href='#{$firstletter}'>".$firstletter."</a> ";
$current = $firstletter;
}
$postlist .= "<a href='$link'>" . $category->cat_name . "</a><br>";
}
$postlist .= "</div>";
The first div remain empty, but all other are ok.

Categories