PHP - increment in recursive function - php

I have this function:
function show_comments(&$comments, $parent_id = 0 ) {
$comments_list = "";
$i = 0;
foreach($comments as $comment) :
if ($comment["parent_id"] != $parent_id)
continue;
$comments_list .= '<div class="comment level-'. $i . '">';
$i++;
$comments_list .= "<p>$comment[body]</p>";
$comments_list .= $this->show_comments($comments, $comment['id_comment']);
$comments_list .= '</div>';
endforeach;
return $comments_list;
}
I want for the parent div to have class level-0 and the direct child of that parent have level-1 and child of child with level-1 to have class level-2 and so on. How can I do this?

// add a new parameter --------------------------------
// |
function show_comments(&$comments, $parent_id = 0, $level = 0) {
$comments_list = "";
// not needed
// $i = 0;
foreach($comments as $comment) :
if ($comment["parent_id"] != $parent_id)
continue;
// use the level parameter ------------------------
// |
$comments_list .= '<div class="comment level-'. $level . '">';
// not needed
// $i++;
$comments_list .= "<p>$comment[body]</p>";
// increment it on recursive calls -----------------------------------------
// |
$comments_list .= $this->show_comments($comments, $comment['id_comment'], $level + 1);
$comments_list .= '</div>';
endforeach;
return $comments_list;
}

Related

How to add static li inside dynamic list using php?

I have 5 menu in the website which is coming dynamically :
menu1 menu2 menu3 menu4 menu5
Now I want to add menu6 before menu5 using php.
My code:
foreach ($collection as $category) {
$i++;
$menuCategory = $this->getCategoryAsArray($category, $currentCategory);
$class = '';
$class .= 'nav'. $i;
if($i == 1) {
$class .= ' first';
} elseif ($i == $count) {
$class .= ' last';
}
if($menuCategory['is_active']) {
$class .= ' active';
}
//if($this->hasChildProduct($category)) {
//$class .= ' parent';
//}
if($this->hasChildSubCategory($category)) {
$class .= ' parent';
}
$class .= ' level-top';
$html .= '<li class="level0 '. $class .'">';
$html .= '<a href="'. $menuCategory['url'] .'">';
$html .= '<span>'. $menuCategory['name'] .'</span>';
$html .= '</a>';
//if($this->hasChildProduct($category)) {
//$html .= $this->getChildProductMenuHtml($category, $i);
//}
if($this->hasChildSubCategory($category)) {
$html .= $this->getChildSubcategoryMenuHtml($category, $i);
}
$html .= '</li>';
}
Menu6 is the static link which code is:
<li class="vertical-submenu" id="static-menu"><a href="<?php echo $block->getUrl('menu6')?>"><?php echo __('menu6')?></li>
I am not getting the code because i am not aware of values coming in the array in foreach loop.
But I can explain the situation to you via Algorithm.
$i = 0;
foreach(expression){
if(value == "menu5"){
write("Menu 4")
}
Write("Menu ".$i)
$i++;
}
Hope your problem is resolved with this. If you need anything else or want to elaborate more about you problem text me at shahrukhusmaani#gmail.com

php - foreach loop, custom slide

It should be a slider, which shows all posts, but only 15 posts on each slide. I get all Posts.
(I use Wordpress functions.)
In the -div class = "slide"- there are 15 posts, after that a new -div class = "slide"- with 15 posts should be created.
Here is the code for all posts:
$myposts = get_posts($args);
$result = '<div id="fullpage">';
$result .= '<div class="section" id="section1">';
$result .= '<div class="slide">';
foreach ($myposts as $post) {
$result .= '' . $post->post_title . '';
// the_post_thumbnail('full');
}
$result .= '</div>';
$result .= ' </div>';
$result .= '</div>';
return $result;
After 15 posts, I would like a new slide. I do not know how to adjust the foreach loop. Should I do this with an if statement, or can I do this with a foreach loop?
Use a counter, and reset it after 15. (Not tested, I have no PHP at the moment)
$counter = 1;
foreach ($myposts as $post) {
if ($counter == 1) {
$result .= '<div class="slide">';
}
$result .= '' . $post->post_title . '';
$counter++;
if ($counter == 16) {
$counter = 1;
$result .= '</div>';
}
}

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';>

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(); }

Category navigation in navigation child

I have a problem with navigation in Magento. The child categories displays in a funny way, which i do not want them too. Please see the following screenshot:
http://tinypic.com/r/2l97byp/8
In upper left, the childs are shown in the menu. However i do not want them to expanding into a new block, but simply show below their parrent category as seen in this picture:
tinypic.com/r/16l0kk3/8
I have two sets of code for this, however i do not know what to edit to get the desired result. I have tried to get it to work, but with no luck.
The two code parts:
top.phtml:
<?php
/**
* Top menu for store
*
* #see Olegnax_Navigation_Block_Navigation
*/
?>
<?php
/**
* $this->renderCategoriesMenuHtml() supports optional arguments:
* int Level number for list item class to start from
* string Extra class of outermost list items
* string If specified wraps children list in div with this class
*/
?>
<!-- navigation BOF -->
<?php $_menu = $this->renderCategoriesMenuHtml(0, 'level-top', 'sub-wrapper' ) ?>
<?php if($_menu): ?>
<nav class="olegnax">
<ul id="nav">
<?php if (Mage::getStoreConfig('celebritysettings/celebritysettings_header/navigation_home')): ?>
<li class="level0 level-top">
<span><?php echo $this->__('Home'); ?></span>
</li>
<?php endif; ?>
<?php
echo $_menu;
$custom_tab = Mage::getModel('cms/block')->load('celebrity_navigation_block');
if($custom_tab->getIsActive()) {
echo '
<li class="level0 level-top parent custom-block">
<a href="#" class="level-top">
<span>'.$custom_tab->getTitle().'</span>
</a>
<div class="sub-wrapper">'.$this->getLayout()->createBlock('cms/block')->setBlockId('celebrity_navigation_block')->toHtml().'</div>
</li>';
}
?>
</ul>
</nav>
<?php endif ?>
<!-- navigation EOF -->
And Navigation.phtml:
<?php
/**
* #version 1.0 12.0.2012
* #author Olegnax http://www.olegnax.com <mail#olegnax.com>
* #copyright Copyright (C) 2010 - 2012 Olegnax
*/
class Olegnax_Navigation_Block_Navigation extends Mage_Catalog_Block_Navigation
{
/**
* columns html
*
* #var array
*/
protected $_columnHtml;
/**
* Render category to html
*
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #param boolean Whether ot not this item is first, affects list item class
* #param boolean Whether ot not this item is outermost, affects list item class
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #param boolean Whether ot not to add on* attributes to list item
* #return string
*/
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>';
if ( $level == 0 ) {
//get category description
$ca = Mage::getModel('catalog/category')->load($category->getId());
$description = $ca->getDescription();
if ( empty($description) || !Mage::getStoreConfig('celebritysettings/celebritysettings_navigation/show_description') ) {
$columns = 4;
} else {
$columns = 2;
}
$columnItemsNum = array_fill(0, $columns, floor($activeChildrenCount / $columns));
if ( $activeChildrenCount % $columns > 0 ) {
for ($i = 0; $i < ($activeChildrenCount % $columns); $i++ ) {
$columnItemsNum[$i]++;
}
}
$this->_columnHtml = array();
}
// render children
$htmlChildren = '';
$j = 0; //child index
$i = 0; //column index
$itemsCount = $columnItemsNum[$i];
foreach ($activeChildren as $child) {
if ( $level == 0 ) {
$isLast = (($j+1) == $itemsCount || $j == $activeChildrenCount - 1);
if ( $isLast ) {
$i++;
$itemsCount += $columnItemsNum[$i];
}
} else {
$isLast = ($j == $activeChildrenCount - 1);
}
$childHtml = $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
$isLast,
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
if ( $level == 0 ) {
$this->_columnHtml[] = $childHtml;
} else {
$htmlChildren .= $childHtml;
}
$j++;
}
if ( $level == 0 && $this->_columnHtml ) {
$i = 0;
foreach ( $columnItemsNum as $columnNum ) {
$chunk = array_slice($this->_columnHtml, $i, $columnNum);
$i += $columnNum;
$htmlChildren .= '<li '.(count($this->_columnHtml) == $i ? 'class="last"' : '').'><ol>';
foreach ( $chunk as $item ) {
$htmlChildren .= $item;
}
$htmlChildren .= '</ol></li>';
}
}
if ( !empty($description) && !empty($htmlChildren) && Mage::getStoreConfig('celebritysettings/celebritysettings_navigation/show_description') ) {
$htmlChildren .= '<li class="menu-category-description clearfix">'.$description;
if ( Mage::getStoreConfig('celebritysettings/celebritysettings_navigation/show_learn_more') ) {
$htmlChildren .= '<p><button class="button" onclick="window.location=\''.$this->getCategoryUrl($category).'\'"><span><span>'.$this->__('learn more').'</span></span></button></p>';
}
$htmlChildren .= '</li>';
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
} }
I hope someone can see what to do in order to get the effect on the image :)
Best Regards,
Patrick
Well, Alan Storm is correct but for what it is worth, to answer your question 'which file do I edit', the file you edit is Navigation.php. I say this because top.phtml has the line echo $_menu;. Anyway, the code in protected function _renderCategoryMenuItemHtml() is perhaps a little convoluted and when I read the code and think about what you are trying to achieve I think you should either:
a) Try commenting out the lines:
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
in order to remove the mouseover interaction and then see if you can hack the CSS to get the layout you desire
or
b) Throw away all the code in protected function _renderCategoryMenuItemHtml() and start again: rewrite it to display the HTML structure you require using elements of the existing code.

Categories