How to do template tree in PHP? - php

I use this recursive function to build a tree in PHP:
private function getSubscribesTemplate($main = array(), $child = array()) {
foreach ($main as $key => $val) {
if($val->SubscrubeToUsersIdNote > 0){
echo 'Subcategory'. $val->NameCategorysubscribetotype;
} else {
echo '<div class="itm">
<div class="nav-header nav-header-little">' . $val->NameCategorysubscribetotype . ' | Subscribe</div>
<div>// HERE ALL SUBCATEGORIES</div>
</div>';
}
if (isset($child[$val->SubscrubeToUsersType])) {
$this->getSubscribesTemplate($child[$val->SubscrubeToUsersType], array());
}
}
}
My problem is that in the result function I need to get an HTML template like this:
<div class="itm">
<div class="nav-header nav-header-little">Music | Subscribe</div>
<div>Jazz</div>
<div>Rock</div>
<div>Pop</div>
</div>
So to create the parent block with child <div>s. What am I doing wrong in my code?

Move the if block:
<div>';
// HERE ALL SUBCATEGORIES
if (isset($child[$val->SubscrubeToUsersType])) {
$this->getSubscribesTemplate($child[$val->SubscrubeToUsersType], array());
}
echo '</div>';

Related

If / Else in HTML within a return of PHP function

I am trying to use an if/else statement within an HTML structure of a return in a PHP function:
function price_vat() {
global $product;
$condition = $product->get_attribute( 'pa_condition' );
return'
<div class="condition-container">
<div class="condition-wrapper">
<?php if($condition = "New"){ ?>
<div id="content-banned">New</div>
<?php } else { ?>
<div id="content-not-banned">Used</div>
<?php } ?>
</div>
</div>
';
}
I am sure it is just a syntax issue here, does anyone have any ideas? Also tried with a tertiary operator but couldn't get it to work. Any input is appreciated.
You can't do like that. You try to put php code in a php code with a return of a function. Try that (I don't test it) :
function price_vat() {
global $product;
$condition = $product->get_attribute( 'pa_condition' );
$html = '<div class="condition-container"><div class="condition-wrapper">';
if($condition == "New")
$html .= '<div id="content-banned">New</div>';
else
$html .= '<div id="content-not-banned">Used</div>';
$html .= '</div></div>';
return $html;
}

PHP breadcrumb array, link is not full

I go the following code for breadcrumb :
<?php
class Breadcrumb
{
private $breadcrumb;
private $separator = ' / ';
private $domain = 'example.org';
public function build($array)
{
$breadcrumbs = array_merge(array('Home' => ''), $array);
$count = 0;
foreach($breadcrumbs as $title => $link) {
$this->breadcrumb .= '
<span itemscope="" itemtype="https://schema.org/BreadcrumbList">
<a href="'.$this->domain. '/'.$link.'" itemprop="url">
<span itemprop="title">'.$title.'</span>
</a>
</span>';
$count++;
if($count !== count($breadcrumbs)) {
$this->breadcrumb .= $this->separator;
}
}
return $this->breadcrumb;
}
}
?>
I call it as follow:
<?php
$breadcrumb = new Breadcrumb();
echo $breadcrumb->build(array(
$pageTitle => 'about',
'More' => 'more.php'
));
?>
pageTitle is a var on top of each page.
The output is correct and shows: Home / About / More
but, the link on each one of them is as follow:
Home: example.org
About: example.org/about
More: example.org/more.php
And I am looking for output like that: example.org/about/more.php
Thank you very much!
You can concatenate the links as you progress through your loop...
$bclink = '';
foreach($breadcrumbs as $title => $link) {
if ($link != '') {
$bclink .= '/' . $link;
}
$this->breadcrumb .= '
<span itemscope="" itemtype="https://schema.org/BreadcrumbList">
<a href="'.$this->domain.$bclink.'" itemprop="url">
<span itemprop="title">'.$title.'</span>
</a>
</span>';
$count++;
if($count !== count($breadcrumbs)) {
$this->breadcrumb .= $this->separator;
}
}

Hiding php echo output with json and ajax request

I'm having the problem running php script right when the page loads, and the output is then displayed on the page, which I dont actually want to display. I tried to hide echo with.
<div style='display:none>
but, still doesn't work. I have an idea that "Ajax and JSON Encode function()" will help me to solve this issue of 'making ajax request to same page'. But, I real don't know how to create an array to encode html and php variable that are responsible for the results. Help please.
Here's my ajax function to show the output.
function mass()
{
$.ajax({
url: "page.php",
cache: false,
success: function(html){
$("#container").html(html);
}
});
}
Here's my php script that hold the output of the page
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysql_query($query);
if (isset($_REQUEST['AnswerId'])){
$AnswerId = $_REQUEST['AnswerId'];
}
else {
$AnswerId = 0;
}
$i=0;
while ($mytablerow = mysql_fetch_row($result)) {
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
if (! $treeArray) {
return;
}
foreach($treeArray as $item) {
if ($item[1] == $pid) {
?>
<div class="Div" style="margin-left:<?php echo($level*60);?>px">
<div class="CotDiv">
<div class="ser"><?php echo($item[2]) ; ?></div>
<div class="Mse"><?php echo($item[3]) ; ?></div>
<div class="ito"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=40) {
echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0]){?>
<div id="InnerDiv"><?php ShowForm($AnswerId);?</div><?php ?> </div><?php
echo ('<br/>');
tree($treeArray, $level+1, $item[0]);
}
}
}
tree($mytable, 0);
?>
#enance this isn't the exact same code, but the idea is the same. This probably doesn't output correctly because I don't have an example array of the mysql output to test.
Just a few notes, try not to use globals and just pass the variable into the function. For the sake of time, I kept the output of html within this function, but ideally you'll like to output html through another function.
<?php
// example array
$mytable = [
[1,0,3,4,5,6],
[0,2,3,4,5,6]
];
$answer_id = 1;
function tree($answer_id, $items, $level, $pid = 0) {
if (empty($array))
return;
foreach ($items as $item) {
if ($item[1] == $pid) {
echo sprintf('<div class="Div" style="margin-left:%spx">',$level * 60);
echo '<div class="CotDiv">';
echo sprintf('<div class="ser">%s</div>', $item[2]);
}
if ($level <= 40) {
echo sprintf('Reply', $item[0]);
echo sprintf('Delete', $item[0]);
}
echo '</div>';
if ($answer_id == $item[0]) {
echo sprintf('<div id="InnerDiv">%s</div>', 'FORM OUTPUT HERE');
tree($answer_id, $items, $level++, $item[0]);
}
echo '</div>';
}
}
tree($answer_id, $mytable, 0);
exit;
I really hope this helps to get you on the right track.

PHP Database driven Multilevel Menu

I want to built a database driven multilevel menu I got it from [http://abhijitpal.in/][1] but the problem here is i can't put class = "dropdown" only to the top menus <ul>, it also get applies to the sub menus as well. I just modified a little but I don't know how to use recursive function. Below is the code, please see if you can help
<?php /** Function to display Catelogue Menu */
//select all rows from the main_menu table
$q ="SELECT * FROM catelogue WHERE cat_visibility = '1'";
$r = mysqli_query($dbc, $q);
//create a multidimensional array to hold a list of menu and parent menu
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
//build the array lists with data from the menu table
while ($row = mysqli_fetch_assoc($r)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['cat_id']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['cat_parentid']][] = $row['cat_id'];
}
// Create the main function to build milti-level menu. It is a recursive function.
function nav_catelogue($parent, $menu) {
//$html = "";
if (isset($menu['parent_menus'][$parent])) { ?>
<ul>
<?php
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) { ?>
<li><?php echo $menu['menus'][$menu_id]['cat_name']; ?></li>
<?php }
if (isset($menu['parent_menus'][$menu_id])) { ?>
<li><?php echo $menu['menus'][$menu_id]['cat_name']; ?>
<?php echo nav_catelogue($menu_id, $menu); ?>
</li>
<?php }
} ?>
</ul>
<?php }
}
?>
My Database structure is
-----------------------------------------
| cat_id | cat_name | cat_parentid |
-----------------------------------------
| 1 | Home | 0 |
| 2 | About | 0 |
| 3 | Contact | 0 |
| 4 | History | 2 |
| 5 | Services | 2 |
-----------------------------------------
Desired Output I want:
HOME
ABOUT
History
Services
Contact
This is the final code as per #Mave
<?php /** Function to display Catelogue Menu */
//select all rows from the main_menu table
$q ="SELECT * FROM catelogue WHERE cat_visibility = '1'";
$r = mysqli_query($dbc, $q);
//create a multidimensional array to hold a list of menu and parent menu
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
//build the array lists with data from the menu table
while ($row = mysqli_fetch_assoc($r)) {
//creates entry into menus array with current menu id ie. $menus['menus'][1]
$menu['menus'][$row['cat_id']] = $row;
//creates entry into parent_menus array. parent_menus array contains a list of all menus with children
$menu['parent_menus'][$row['cat_parentid']][] = $row['cat_id'];
}
// Create the main function to build milti-level menu. It is a recursive function.
function nav_catelogue($parent, $menu, $top = false) {
if (isset($menu['parent_menus'][$parent])) {
//this is short code for if($top === true) { //do true } else { //do false }
echo $top ? '<ul class="dropdown">' : '<ul>';
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
echo '<li>' . $menu['menus'][$menu_id]['cat_name'] . '</li>';
}
if (isset($menu['parent_menus'][$menu_id])) {
echo '<li>' . $menu['menus'][$menu_id]['cat_name'] . '' . nav_catelogue($menu_id, $menu) . '</li>';
}
}
echo '</ul>';
}
}
?>
function nav_catelogue($parent, $menu, $top = false) {
if (isset($menu['parent_menus'][$parent])) {
//this is short code for if($top === true) { //do true } else { //do false }
echo $top ? '<ul class="dropdown">' : '<ul>';
foreach ($menu['parent_menus'][$parent] as $menu_id) {
if (!isset($menu['parent_menus'][$menu_id])) {
echo '<li>' . $menu['menus'][$menu_id]['cat_name'] . '</li>';
}
if (isset($menu['parent_menus'][$menu_id])) {
echo '<li>' . $menu['menus'][$menu_id]['cat_name'] . '' . nav_catelogue($menu_id, $menu) . '</li>';
}
}
echo '</ul>';
}
}
When you first call nav_catelogue (not present in your current code), call it with nav_catelogue($menu_id, $menu, true);
You have two ways to make your recursive function put the
class="dropdown"
The first way is to go for a calling/callee style in which your calling function will treat the first case(class="dropdown") and then call the recursive function which will handle the general case(no class="dropdown").
Add an argument(boolean ?) that you'll transmit at first call and which will add the class="dropdown". On the recursive calls you'll transmit this boolean as false(no class="dropdown" insertion).

Wrap anchor tag content with SPAN using PHP

I need to take some simple UL tag generated in PHP (Joomla 1.5) and wrap each anchor tag's text content with a SPAN tag. The incoming HTML looks like this:
<ul>
<li>
Home
</li>
<li>
Watch UNC-TV
</li>
<li>
<a href="#" >Contact</a>
</li>
</ul>
The output needs to look like this:
<ul id="top-nav" class="flatList">
<li class="selected">
<a href="#"><span class="embed embed-top-nav">Home</span>
<p >news, highlights</p></a>
</li>
<li>
<a href="#"><span class="embed embed-top-nav">Watch UNC-TV</span>
<p>schedule, local programs</p></a>
</li>
<li id="nav-last">
<a href="#"><span class="embed embed-top-nav">Contact</span>
<p>feedback, connect, share</p></a>
</li>
</ul>
Also note the class added to the active LI tag ("selected") and the class added to the last one in the list ("nav-last"). This is in Joomla 1.5, where I'm overriding the mod_mainmenu module used by the Main Menu. The code uses the SimpleXML library to read and write the HTML in the modMainMenuXMLCallback(&$node, $args):
<?php
defined('_JEXEC') or die('Restricted access');
if ( ! defined('fancyMenuPatch') )
{
function fancyMenuPatch($result,$tag){
// Replace UL tag with ours.
// Replace LI tag with ours.
// Add to the start of the UL tag.
$begin_ul = "<ul id=\"top-nav\" class=\"flatList\">";
$begin_li = "<li>"; //not sure what to do with this.
// do the replacement
$result = str_replace("<ul>",$begin_ul, $result);
$result = str_replace("<li>", $begin_li, $result);
return $result;
}
define('fancyMenuPatch', true);
}
if ( ! defined('modMainMenuXMLCallbackDefined') )
{
function modMainMenuXMLCallback(&$node, $args)
{
$user = &JFactory::getUser();
$menu = &JSite::getMenu();
$active = $menu->getActive();
$path = isset($active) ? array_reverse($active->tree) : null;
if (($args['end']) && ($node->attributes('level') >= $args['end']))
{
$children = $node->children();
foreach ($node->children() as $child)
{
if ($child->name() == 'ul') {
$node->removeChild($child);
}
}
}
if ($node->name() == 'ul') {
foreach ($node->children() as $child)
{
if ($child->attributes('access') > $user->get('aid', 0)) {
$node->removeChild($child);
}
}
}
if (($node->name() == 'li') && isset($node->ul)) {
$node->addAttribute('class', 'parent');
}
if (isset($path) && (in_array($node->attributes('id'), $path) || in_array($node->attributes('rel'), $path)))
{
if ($node->attributes('class')) {
$node->addAttribute('class', $node->attributes('class').' active');
} else {
$node->addAttribute('class', 'active');
}
}
else
{
if (isset($args['children']) && !$args['children'])
{
$children = $node->children();
foreach ($node->children() as $child)
{
if ($child->name() == 'ul') {
$node->removeChild($child);
}
}
}
}
if (($node->name() == 'li') && ($id = $node->attributes('id'))) {
if ($node->attributes('class')) {
$node->addAttribute('class', $node->attributes('class').' item'.$id);
} else {
$node->addAttribute('class', 'item'.$id);
}
}
if (isset($path) && $node->attributes('id') == $path[0]) {
$node->addAttribute('id', 'current');
} else {
$node->removeAttribute('id');
}
$node->removeAttribute('rel');
$node->removeAttribute('level');
$node->removeAttribute('access');
}
define('modMainMenuXMLCallbackDefined', true);
}
ob_start();
modMainMenuHelper::render($params, 'modMyMainMenuXMLCallback');
$menu_html = ob_get_contents();
ob_end_clean();
if($params->get('menutype')=="primarynav"){
$tag = $params->get('tag_id');
}
//output the menu!
echo fancyMenuPatch($menu_html,$tag);
?>
Thank you.
Ok so here is how you want to do this. Jump out of the default.php script you posted above. As Joomla! uses the core mainmenu module for all menus and trees down from that you will need to edit the helper script. This should stick regardless of any 3rd party menu extension you may be using.
rootdirectory/modules/mod_mainmenu/helper.php
Now jump down to the switch statement at line 358. Specifically we want to edit line 363. It looks like this:
$data = ''.$image.$tmp->name.'';
Now edit it to be this:
$data = '<span class="embed embed-top-nav">'.$image.$tmp->name.'</span>';
there you go, now menus utilized by the Joomla! getMenu class will add this span tag around the links.
Note that you may also want to do this to line 375 for links that will open in a new window et cetra. Also note Louis' funny comment " // hrm...this is a bit dickey".
cheers

Categories