find last child in recursive function - php

recursive function
im trying to achieve above condition.
i have successful list parent and multi-level child title in tab title section
Now in Tab Content im trying to list content for the title listed in Tab title
In Tab Content if parent have multi-level child then only last child content should display but if parent does have any child then parent content should display
But im getting content for all title parent as well as nested child here i want last child content only but if parent does have child then parent content should be displayed
how to check if parent have any child, if parent have child then display content for last child only, if parent doesn’t have child then display parent content
Code for displaying Multi-level-nested child Title in Tab Title
$categoryMulti = array(
'categories' => array(),
'parent_cats' => array()
);
$sql = "SELECT `id`, `parent_id`, `name`, `content` FROM categories";
$query = $conn->query($sql);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$categoryMulti['categories'][$row['id']] = $row;
$categoryMulti['parent_cats'][$row['parent_id']][] = $row['id'];
}
//title for tabs
function listCategoryTree($parent, $category)
{
$css_class = ($parent == 0 ? "parent" : "child");
$html = '';
if (isset($category['parent_cats'][$parent])) {
$html .= '<ul class="im-'.$css_class.'">'."\n";
foreach ($category['parent_cats'][$parent] as $cat_id) {
if (!isset($category['parent_cats'][$cat_id])) {
$html .= '<li id="">
<a href="" data-cap= "'.$css_class.'-'.$cat_id.'">'
. $category['categories'][$cat_id]['name'] .
'</a>';
'</li>'."\r";
} else {
$html .= '<li id="">
<a href="" data-cap= "'.$css_class.'-'.$cat_id.'">'
. $category['categories'][$cat_id]['name'] .
'</a> <span>arrow icon </span>'."\r";
$html .= listCategoryTree($cat_id, $category);
$html .= '</li>'."\r";
}
}
$html .= '</ul>'."\n";
}
return $html;
}
Code trying to display last child content if parent have multi-level-nested child and if parent does have any child display parent content
but its display content for all nested-child and parent content too.
//content for tabs
$contentTab = array(
'contentCat' => array(),
'contentChild' => array()
);
$sql = "SELECT `id`, `parent_id`, `name`, `content` FROM categories";
$query = $conn->query($sql);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$contentTab['contentCat'][$row['id']] = $row;
$contentTab['contentChild'][$row['parent_id']][] = $row['id'];
}
function listContentTree($parent, $category)
{
$css_class = ($parent == 0 ? "parent" : "child");
$html = '';
if (isset($category['contentChild'][$parent])) {
$html .= '<ul class="im-'.$css_class.'">'."\n";
foreach ($category['contentChild'][$parent] as $cat_id) {
if (!isset($category['contentChild'][$cat_id])) {
$html .= '<li id="'.$css_class.'-'.$cat_id.'">
<a href="" data-cap= "">im child content test---'
. $category['contentCat'][$cat_id]['content'] .
'</a>';
'</li>'."\r";
} else {
$html .= '<li id="'.$css_class.'-'.$cat_id.'">
<a href="" data-cap= "">hello parent test------'
. $category['contentCat'][$cat_id]['content'] .
'</a>'."\r";
$html .= listContentTree($cat_id, $category);
$html .= '</li>'."\r";
}
}
$html .= '</ul>'."\n";
}
return $html;
}
how check to for last child.
if(has last child){
then display content of last child
}else{
//where parent doesnt have any child
display content of parent
}

Related

Remove Icon Arrow if Category haven't Sub-category in Laravel

enter code hereDoes any one can advice me how to remove the icon for main category havent's sub-categories.
I have pass to show sub-categories under main category.
Here is my code:
[enter image description here][1]
My view:
[blade View][2]
[1]: https://i.stack.imgur.com/MbDuB.png
[2]: https://i.stack.imgur.com/ieAqL.png
My Update with code
public static function showCategories($categories, $parent_id = 0)
{
$class ='';
$html = ""; //init
$flag = false;
foreach ($categories as $row) {
if ($row['parent_id'] == $parent_id) {
//we have a category
$link =self::linkCategory($row['category_id'],$row['name']);
$html .= '<ul id="accordion" class="accordion">
<li>
<div class="link accordion-title">'.$row['name'].'<i class="fa fa-chevron-down"></i></div>';
$html .= "<ul class='submenu'>";
foreach ($categories as $subcat) {
$link =self::linkCategory($subcat['category_id'],$subcat['name']);
if ($subcat['parent_id'] ==$row['category_id']){
//we have a subcategory
$html .= '<li>'.$subcat['name'].'</li>';
}
}
$html .= "</ul>";
$html .= "</li>";
$html .= "</ul>";
}
}
return $html;
//call it blade
$menu = URL::showCategories($itemCategory);
first of all its a bad practice that you use HTML in control, you have to use HTML only in blade sec you can do that by making the relation between categories and itself to get the sub cat to every cat then if your blade while you are looping it u can easily use Count() to get number of sub cat if it bigger than 0
add icon if don't add it
#if(Count($cat->sub) > 0)
<i class="icon-class">
#endif

Magento diplaying category tree dynamically

I need to display my category tree as a list in a responsive menu.
The idea is to display the highest level categories. and create dynamically a list that will be displayed for each category that has children.
I stumbled upon a code that helped me a bit, but i can't figure how to get the job done.
Here is the code:
<?php
$rootCatId = Mage::app()->getStore()->getRootCategoryId();
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentId));
$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
$children = Mage::getModel('catalog/category')->getCategories(7);
foreach ($children as $category) {
{
$html .= '<li>'.$category->getName()."";
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;
?>
Thank you in advance.
you can use this to create category tree:
<?php
$rootCatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootCatId);
$output= '<ul>';
foreach($categories as $category) {
$cat = Mage::getModel('catalog/category')->load($category->getId());
$count = $cat->getProductCount();
$output .= '<li>' . '' . $category->getName() . "";
if ($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$array .= get_categories($children);
}
$output .= '</li>';
}
echo $output . '</ul>';
?>
For the effects of showing / hiding categories and subcategories, you can use plain css or jQuery / Prototype.

Variable Anchor tags inside a variable post Wordpress

i have a very long article created by a user in Wordpress , i want to show a navigation on every article page with links to the titles of the current article.
e.g:
<h1 id='title1'>Title 1</h1>
bla bla bla
<h1 id='title2'>Title 2</h1>
bla bla
my navigation on this page would be Anchor link to title 1
The example above is how you would hardcode it, but my article text is obviously variable and so are my links, what is the best way to tackle this with php?
Edit: the situation is not exactly like the example, the user puts text into a wordpress text editor field and doesnt want to write html tags, so the navigation needs to be filled with the titles that the user has put in the text field and those link to the variable titles on the page. (with an anchor i assume)
the functionality would be something like Microsoft word:
You can filter the content in order to target the different titles, add an ID in a form of a slug using sanitize_title on each of them and build a hierarchical array of those titles in order to display the anchor menu on top of the post.
I just wrote this filter for the example, but it is totally not tested so you may have to debug it a bit and change it depending of your needs. Please note that it works for a 3 level hierarchy maximum.
function add_anchor_menu($content) {
// First you may want to do some check here to see if this filter should be trigger on the current post...
$arrayTitles = array();
// Generate the ids...
$content = preg_replace_callback(
'#<h([1-3])>(.*?)<\/h[1-3]>#',
function($matches) {
$id = sanitize_title($matches[2]);
$meta = array('id' => $id, 'title' => $matches[2], 'childs' => array());
if((int)$matches[1] == 1) {
array_push($arrayTitles, $meta);
} elseif((int)$matches[1] == 2) {
end($arrayTitles);
array_push($arrayTitles[key($arrayTitles)]['childs'], $meta);
} else {
end($arrayTitles);
end($arrayTitles[key($arrayTitles)]['childs']);
array_push($arrayTitles[key($arrayTitles)]['childs'][key($arrayTitles[key($arrayTitles)])], $meta);
}
return '<h' . $matches[1] . ' id="' . $id . '">' . $matches[2] . '</h' . $matches[1] . '>';
},
$content
);
// And generate the menu...
if(count($arrayTitles) > 0) {
$menu = '<ul id="anchor-menu">';
foreach($arrayTitles as $level1) {
$menu .= '<li>';
$menu .= '' . $level1['title'] . '';
if(count($level1['childs']) > 0) {
$menu .= '<ul>';
foreach($level1['childs'] as $level2) {
$menu .= '<li>';
$menu .= '' . $level2['title'] . '';
if(count($level2['childs']) > 0) {
$menu .= '<ul>';
foreach($level2['childs'] as $level3) {
$menu .= '<li>' . $level3['title'] . '</li>';
}
$menu .= '</ul>';
}
$menu .= '</li>';
}
$menu .= '</ul>';
}
$menu .= '</li>';
}
$menu .= '<ul>';
$content = $menu . $content;
}
return $content;
}
add_filter('the_content', 'add_anchor_menu');
In your mark up
<h1 id="<?php echo get_the_title(); ?>">Title 1</h1>
Anchor link to title 1
You should esc_url() in the href attribute as well.

dynamic custom menu php

trying to get some thing like that dynamically
<ul>
<li>Home</li>
<li>About Us</li>
<li>Academics
<ul style="overflow: hidden; display: block; height: 0px; z-index: 51; opacity: 0.00980392;">
<li>Bs Computer Science</li>
<li>Diplomas (DIT & DCHE)</li>
<li>MBAIT</li>
</ul>
</li>
<li><a class=" " href="#">College</a>
</ul>
the code is
<?php
//========================================================
$result = mysql_query(" SELECT id, parentId, name
FROM
menu
ORDER BY
parentId, name");
$menuData = array(
'items' => array(),
'parents' => array()
);
while ($menuItem = mysql_fetch_assoc($result))
{
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
function buildMenu($parentId, $menuData)
{
$html = '';
if (isset($menuData['parents'][$parentId]))
{
$html = '<ul id="main_menu">';
foreach ($menuData['parents'][$parentId] as $itemId)
{
$html .= '<li>' . $menuData['items'][$itemId]['name'];
// find childitems recursively
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
//=======================================================
?>
above code is showing only first parents elements in the menu and the remaing elements are not showing.. the menu is not working correctly becoz of the class id is not given in the ul tag.. and by writing this
echo '<ul id="main_menu">';
// output the menu
echo buildMenu(0, $menuData);
echo "</ul>";
it shows nothing in the menu
Ok, try this:
<?php
//========================================================
$result = mysql_query(" SELECT id, parentId, name, link
FROM
menu
ORDER BY
parentId, name");
$menuData = array(
'items' => array(),
'parents' => array()
);
while ($menuItem = mysql_fetch_assoc($result)) {
$menuData['items'][$menuItem['id']] = $menuItem;
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}
function buildMenu($parentId, $menuData)
{
$html = '';
if (isset($menuData['parents'][$parentId]) && count( $menuData['parents'][$parentId] ) > 0 ) {
if( $parentId == "0" ){
$html = '<ul id="main_menu">';
}else{
$html = '<ul id="sub_menu">';
}
foreach ($menuData['parents'][$parentId] as $itemId) {
$html .= '<li>';
$html .= strlen($menuData['items'][$itemId]['link']) > 2?
''.$menuData['items'][$itemId]['name'].'':
$menuData['items'][$itemId]['name'];
$html .= buildMenu($itemId, $menuData);
$html .= "</li>";
}
$html .= '</ul>';
} else {
$html .= '<li>' . $menuData['items'][$parentId]['name'].'</li>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
//=======================================================
?>

Drupal Adding Span inside A tags in Nice Menus

I am trying to add drop down menus to a drupal theme which uses text sliding door CSS rounding.
The current version uses a primary links injection of the span into the a tags, which works fine. But doesn't support drop down menus.
Working code:
<?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
In the template with a template.php file addition:
<?php
// function for injecting spans inside anchors which we need for the theme's rounded corner background images
function strands_guybrush_links($links, $attributes = array('class' => 'links')) {
$output = '';
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = $key;
// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))) {
$class .= ' active';
}
$output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
if (isset($link['href'])) {
$link['title'] = '<span class="link">' . check_plain($link['title']) . '</span>';
$link['html'] = TRUE;
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
return $output;
}
?>
So I have added the Nice Menu module which works well and allows the drop down menu functions for my navigation which is now addressed from the template using:
<?php print theme_nice_menu_primary_links() ?>
The issue is that the a tags need to have spans inside to allow for the selected state markup. I have tried every angle I could find to edit the drupal function menu_item_link which is used by nice menus to build the links.
E.g. I looked at the drupal forum for two days and no joy.
The lines in the module that build the links are:
function theme_nice_menu_build($menu) {
$output = '';
// Find the active trail and pull out the menus ids.
menu_set_active_menu_name('primary-links');
$trail = menu_get_active_trail('primary-links');
foreach ($trail as $item) {
$trail_ids[] = $item['mlid'];
}
foreach ($menu as $menu_item) {
$mlid = $menu_item['link']['mlid'];
// Check to see if it is a visible menu item.
if ($menu_item['link']['hidden'] == 0) {
// Build class name based on menu path
// e.g. to give each menu item individual style.
// Strip funny symbols.
$clean_path = str_replace(array('http://', '<', '>', '&', '=', '?', ':'), '', $menu_item['link']['href']);
// Convert slashes to dashes.
$clean_path = str_replace('/', '-', $clean_path);
$class = 'menu-path-'. $clean_path;
$class .= in_array($mlid, $trail_ids) ? ' active' : '';
// If it has children build a nice little tree under it.
if ((!empty($menu_item['link']['has_children'])) && (!empty($menu_item['below']))) {
// Keep passing children into the function 'til we get them all.
$children = theme('nice_menu_build', $menu_item['below']);
// Set the class to parent only of children are displayed.
$class .= $children ? ' menuparent ' : '';
// Add an expanded class for items in the menu trail.
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']);
// Build the child UL only if children are displayed for the user.
if ($children) {
$output .= '<ul>';
$output .= $children;
$output .= "</ul>\n";
}
$output .= "</li>\n";
}
else {
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']) .'</li>'."\n";
}
}
}
return $output;
}
As you can see the $output uses menu_item_link to parse the array into links and to added the class of active to the selected navigation link.
The question is how do I add a span inside the a tags OR how do I wrap the a tags with a span that has the active class to style the sliding door links?
If you want to wrap the a tags with a span, you can overwrite the theme_nice_menu_build and add your span to the output. If you want to inside the a tag you need to overwrite the menu_item_link.
You can overwrite a theme funciton by creation a function call your_theme_name_function_name and Drupal will use that function to render the markup instead of the default one. That way you can alter the markup any way you want. This function should be in your theme's template.php file.
A good way to start is to copy the function you want to overwrite and just alter to your likings.
A lot has happened since Drupal 4.7, I don't hope you use that. It's quite easy to insert span tags:
function your_theme_name_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
$link['localized_options']['html'] = TRUE;
return l('<span>' . $link['title'] . '</span>', $link['href'], $link['localized_options']);
}
I tested this and it works just fine.

Categories