Tree iteration without recursion - php

So, I was trying to print my class:
class category {
public $name;
public $id;
public $subCats = array();
public function __construct($name = "", $id = "") {
$this->name = $name;
$this->id = $id;
}
public function add_sub_cat($subCat) {
array_push($this->subCats, $subCat);
}
}
In two ways recursive and iterative, first one I did without any problems:
function recursive_print($category, $path) {
?>
<li><div id="category-name" ><p><? echo $category->name ?></p>
</div></li>
<?php foreach($category->subCats as $subCat) { ?>
<ul>
<?php recursive_print($subCat, $path.=$subCat->id) ?>
</ul>
<?php }
}
But now I got stuck on second part of this task.
Do I have to modify my class?
Is it even possible to print without recursion?
I have read this but it did not cleared anything.
Maybe someone have better tutorial or any advice?

Walking a tree without recursion is always an interesting problem.
The basic idea is you need to keep track of a stack by yourself. (Function calls are implemented by pushing temporary variables and a return address to a stack before the call, and popping that return address afterwards, so when you make a recursive function, you're avoiding having to do this yourself.)
Here's a non-recursive implementation:
function tree_print($root_category) {
$stack = array(array($root_category));
echo '<ul>'."\n";
while (count($stack)) {
$category = array_shift($stack[count($stack)-1]);
echo '<li><div id="category-name"><p>' . $category->name . '</p></div></li>'."\n";
echo '<ul>'."\n";
$stack[] = $category->subCats;
while (count($stack) && count($stack[count($stack)-1]) == 0) {
echo '</ul>'."\n";
array_pop($stack);
}
}
}
In each iteration round the main loop, we shift the first tree node from the array at the top of the stack, print it, open a <ul> tag, and push to the stack an array of all its child nodes. Then, we get rid of any empty arrays from the top of the stack, closing one <ul> tag for each such empty array.
See it running here: https://3v4l.org/umpvf

Related

PHP function with for each loop inside - what to return?

I have navigation with product categories at top of website.
Want to repeat this navigation in footer of website.
Instead of writing $args, defining variables and such once again I decided to make a function for this.
It looks like this:
However as every function should have a return I'm confused how should return of this function look like?
When I try to return <li> instead of echoing it - I get nothing, empty area, but with echo - function works.
Instead of echo you can write $return_data .= ... to concatenate a string which was initially declared as an empty string before the loop began.
Here is a sample for such cases:
function show_prod_cats($all_categories) {
$return_data = '';
foreach ($all_categories as $cat) {
//echo '<li>....</li>';
$return_data .= '<li>....</li>';
}
return $return_data;
}

Can't get all link in a div

I'm trying to get all link from this page. Actually there I almost achieve this result with this code:
public function getLinks()
{
$html = file_get_html("http://it.soccerway.com/national/italy/serie-a/20152016/regular-season/r31554/");
foreach($html->find("div.block_competition_left_tree-wrapper") as $div)
{
foreach ($div->find('a') as $li)
{
echo $li->href . "<br>";
}
}
}
this is the result:
/national/italy/serie-a/c13/
/national/italy/serie-a/20152016/s11663/
/national/italy/serie-b/c14/
/national/italy/serie-c1/c53/
/national/italy/serie-c2/c358/
/national/italy/serie-d/c659/
/national/italy/coppa-italia/c135/
/national/italy/super-cup/c171/
/national/italy/coppa-italia-serie-c/c684/
/national/italy/campionato-nazionale-primavera/c952/
/national/italy/coppa-italia-primavera/c1070/
/national/italy/super-coppa-primavera/c1171/
/national/italy/dante-berretti/c1092/
/national/italy/serie-a-women/c293/
/national/italy/serie-a2/c457/
/national/italy/coppa-italia-women/c852/
/national/italy/super-cup-women/c851/
/national/italy/club-friendlies/
the problem is that I need to scrape only the link in the list <li>, how you can see in the html there is different classes expanded | odd | even. Essentially I don't want get the link of the element displayed as Serie A - Serie B, etc... but the link inside it. In particular something like this should be the result:
/national/italy/serie-a/20152016/s11663/
/national/italy/serie-b/20152016/regular-season/r31798/
/national/italy/serie-c1/20152016/girone-c/r31861/
now if you see in the first result above there is only /national/italy/serie-a/20152016/s11663/ correct in my final example, this is 'cause in the html page the Serie A item have the class expanded and the code see the link. How can I fix my code to achieve this?
I hope, I have understood you as well. You need to get all links as you did, then open every link to get all links of the class.
An example:
public function getLinks()
{
$html = file_get_html("http://it.soccerway.com/national/italy/serie-a/20152016/regular-season/r31554/");
foreach($html->find("div.block_competition_left_tree-wrapper") as $div)
{
//get all links
foreach ($div->find('a') as $li)
{
$openLink = file_get_html("http://it.soccerway.com/".$li->href);
foreach($openLink->find("div.block_competition_left_tree-wrapper") as $divOfNewLink){
foreach ($divOfNewLink->find('li') as $liOfNewDiv){
if (preg_match("/expanded/i", $liOfNewDiv->class)) {
foreach ($liOfNewDiv->find('a') as $link)
{
echo $link->href . "<br>";
}
}else{
// do nothing
}
}
}
}
}
}

Building a menu system with a PHP class

UPDATE 2 ::
This is the output I am getting from the function right now :
<nav>
<ul> //UL 1
<ul> //UL 2
menu link 1
<li>login</li>
<li>
<ul>sublink3</ul>
</li>
<li><a>menu link 3</a></li>
<li>
<ul>
sublink1
<li>sublink2</li>
</ul>
</li>
<li>menu link 4</li>
<li>menu link 5</li>
<li>
<ul>
sublink5a
<li>sublink5b</li>
<li>sublink5c</li>
<li>sublink5d</li>
</ul>
</li>
</ul> //End of UL 2
<ul></ul> //dont not why this is here?
</ul> //End of UL 1
</nav>
UPDATE
Ok I have re-move the construct, and this is how I am trying to display my menu :
<?php include('./includes/menu.php'); ?>
<h1>HEADER FILE TITLE TEST</h1>
<?php
$build = new Menu;
var_dump($build->DisplayMenu());
?>
I mainly only use CakePHP to build sites with, but I am trying to push my PHP skills up to the next level. So I am looking at other frameworks and OOP (which I have never used within PHP before). So I set myself a little task of building a menu system, controllable from a database e.g. titles and path links come form my db.
This works fine when I just built it has a function put all my menu system items within an array and then used a print call to display the menu, then I just called the function on the page I had required the file to.
But I thought that this was not the best way about doing it, so I wanted to make it a class, so I put a class call around my function, and then changed the print call to a return. What I got form the class/function was a NULL answer when I var dumped it. So I did some research, and re-read a lot about how to declare an array within the magic 'construct' function.
But now I am very confused, should this be inside my Menu function or outside? Just by adding the construct function, it started to display 'string(9)' - which I don't know why? Here is my code :
//Menu Include file
class Menu {
public $testforme = "dfdfdfdf"; //Just a test to see how to call somedata
public function DisplayMenu() {
$DBConn = getConnection(); //Set new database connection
$SQLMainMenu = "SELECT * FROM menu"; //Get Menu setting from database
//$MenuBuild[] = NULL; //Open array for menu to save data into
function __construct($MenuBuild = array()) {
//not sure what to put here???
}
try {
$MenuBuild[] = '<nav><ul>';
//Foreach loop for all main menu links
foreach ($DBConn->query($SQLMainMenu) as $MainMenu) {
$MainMenuID = $MainMenu['id'];
$MainMenuPath = $MainMenu['linkpath'];
$MainMenuSublinkCounts = $MainMenu['sublinks'];
$SQLSubMenu = "SELECT * FROM submenu WHERE menu_id = $MainMenuID";
if ($MainMenuPath == 'NULL') {
$MenuBuild[] = '<li><a>' .$MainMenu['name'] .'</a>';
} else {
$MenuBuild[] = '<li>' .$MainMenu['name'] .'';
}
if ($MainMenuSublinkCounts >=1) { $MenuBuild[] = '<ul>'; }
//Foreach loop to build all inner links for menu
foreach ($DBConn->query($SQLSubMenu) as $SubMenu) {
$SubLinkMenuIDs = $SubMenu['menu_id'];
$SubLinkTitles = $SubMenu['name'];
$SubLinkPaths = $SubMenu['linkpath'];
if ($SubLinkMenuIDs == $MainMenuID) {
$MenuBuild[] = '<li>'. $SubLinkTitles . '</li>'; }
} //End of inner foreach loop
if ($MainMenuSublinkCounts >=1) {
$MenuBuild[] = '</ul>';
}
$MenuBuild[] = '</li>';
} //End of foreach loop
$MenuBuild[] = '</ul></nav>';
//Print the Array that holds the menu.
foreach ($MenuBuild as $MenuKey => $MenuData) {
$MenuSystem = $MenuBuild[$MenuKey]; return $MenuSystem;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
} //End of function DisplayMenu
} //end of class
Now I am connection to my db using a PDO, which is working fine, it within a other file that both are included on.
Please let me know of any good help sites and I have read lots of the questions / answers on here.
Also please go easy on me? this is the 1st time I am using OOP PHP.
If of I am not doing something right, with the way I am building the menu please point at any issues with that :).
Thanks Glenn.
Ok, this is for you, but you really need to do some more research before putting something like this up
my approach encapsulates some functionality but it should seem pretty clear where it's headed just by looking at it. Please feel free to make any questions
(REREedited) includes/menu.php
<?php
class Menu {
private $db;
private $main;
public function __construct($db=null) {
$this->db = $db ? $db : getConnection();
$q = 'SELECT id,name,linkpath,sublinks FROM menu';
$this->main = $this->db->query($q);
}
public function displayMenu() {
$items = array();
foreach ($this->main as $row) {
$path = $row['linkpath'];
$link = self::link($row['name'],$path==='NULL'?null:$path);
// if there is a submenu, concatenate to with the "parent" into the same "item"
if ($row['sublinks'] > 0) $link .= $this->subMenu($row['id']);
$items[] = $link;
}
// returns the whole nav menu.
return '<nav>'.self::lists(array_filter($items)).'</nav>';
}
private function subMenu($id) {
$q = 'SELECT name,linkpath FROM submenu WHERE menu_id = ';
$sub = array();
foreach ($this->db->query($q.$id) as $row) {
$sub[] = self::link($row['name'],$row['linkpath']);
}
return self::lists(array_filter($sub));
}
static function link($content, $href) {
return '<a '.($href?'href="'.$href.'"':'').'>' .$content.'</a>';
}
static function lists(array $items) {
if (!$items) return null;
return '<ul><li>'.implode('</li><li>',$items).'</li></ul>';
}
}
test.php
<?php include('./includes/menu.php'); ?>
<h1>HEADER FILE TITLE TEST</h1>
<?php
try {
$build = new Menu;
echo $build->displayMenu();
} catch (Exception $e) {
echo $e->getMessage().PHP_EOL.$e->getTraceAsString();
}
?>

Laravel 4 - Eloquent. Infinite children into usable array?

I've got a categories table. Each category can have an optional parent (Defaults to 0 if no parent).
What I want to do is build a simple html list tree with the levels of the categories.
Example date:
Foods
-- Fruit
---- Apple
---- Banana
---- Orange
-- Veg
---- Cucumber
---- Lettuce
Drinks
-- Alcoholic
---- Beer
---- Vodka
Misc
-- Household Objects
---- Kitchen
------ Electrical
-------- Cooking
---------- Stove
---------- Toaster
---------- Microwave
Note that this needs to work for around 10 'levels'. I'd love it to be infinite but I really dont want to be going down the route of using a nested set model as it'll cause huge delays on this project.
The docs on this for laravel are terrible, with no real reference as to where to even start. I've been playing with it for days trying to work out what to do and seem to be getting nowhere without a huge messy block of for each loops within each other 10 times.
I've got my tree of data using the following in my model:
<?php
class Item extends Eloquent {
public function parent()
{
return $this->hasOne('Item', 'id', 'parent_id');
}
public function children()
{
return $this->hasMany('Item', 'parent_id', 'id');
}
public function tree()
{
return static::with(implode('.', array_fill(0,10, 'children')))->where('parent_id', '=', '0')->get();
}
}
This gets all the parent and children up to a level of 10. This works fine, but you cant really then do anything with the child data without manually having 10 foreach loops within each other.
What am I doing wrong here? Surely this shouldn't be this hard/poorly executed? All I want do do is get a simple html list with the items in a tree structure.
I've put together a quick SQLFiddle example of the dummy data used above: http://sqlfiddle.com/#!2/e6d18/1
This was much more fun than my usual morning crossword puzzle. :)
Here is an ItemsHelper class that will do what you are looking for, and better yet will recurse as far down as you want.
app/models/ItemsHelper.php:
<?php
class ItemsHelper {
private $items;
public function __construct($items) {
$this->items = $items;
}
public function htmlList() {
return $this->htmlFromArray($this->itemArray());
}
private function itemArray() {
$result = array();
foreach($this->items as $item) {
if ($item->parent_id == 0) {
$result[$item->name] = $this->itemWithChildren($item);
}
}
return $result;
}
private function childrenOf($item) {
$result = array();
foreach($this->items as $i) {
if ($i->parent_id == $item->id) {
$result[] = $i;
}
}
return $result;
}
private function itemWithChildren($item) {
$result = array();
$children = $this->childrenOf($item);
foreach ($children as $child) {
$result[$child->name] = $this->itemWithChildren($child);
}
return $result;
}
private function htmlFromArray($array) {
$html = '';
foreach($array as $k=>$v) {
$html .= "<ul>";
$html .= "<li>".$k."</li>";
if(count($v) > 0) {
$html .= $this->htmlFromArray($v);
}
$html .= "</ul>";
}
return $html;
}
}
I just used a new installation of Laravel 4 and the basic hello.php view.
Here is my route in app/routes.php:
Route::get('/', function()
{
$items = Item::all();
$itemsHelper = new ItemsHelper($items);
return View::make('hello',compact('items','itemsHelper'));
});
Although my view doesn't use the items variable, I'm passing it here because you probably will want to do something else with them too.
And finally, my app/views/hello.php just has one line:
<?= $itemsHelper->htmlList(); ?>
The output looks like this:
FoodsFruitAppleBananaOrangeVegCucumberLettuceDrinksAlcoholicBeerVodkaMiscHousehold ObjectsKitchenElectricalCookingStoveToasterMicrowave
Note: your SQL Fiddle had 5 ("Orange") as the parent_id for Cucumber and Lettuce, I had to change it to 6 ("Veg").
I've expanded on the accepted answer by Mark Smith to allow generated lists to reference addition data that is passed into the class.
The class works in pretty much the same way, but I've packaged it up so hopefully it can be used easily.
Just reference the helper class in your controller:
use App\Helpers\CategoryHierarchy;
You can then either instantiate the class manually, or using Laravel 5's method injection things get even better:
$products = $product->getAllProducts();
$hierarchy->setupItems($products);
return $hierarchy->render();
This can output the following:
<ul class='simple-list'>
<li><input type="checkbox" name="hierarchy-checkboxes[]" value="1" >Home delivery</li>
<ul>
<li><input type="checkbox" name="hierarchy-checkboxes[]" value="2" >Italian</li>
<ul>
<li><input type="checkbox" name="hierarchy-checkboxes[]" value="3" >Pizza</li>
<li><input type="checkbox" name="hierarchy-checkboxes[]" value="4" >Pasta</li>
</ul>
<li><input type="checkbox" name="hierarchy-checkboxes[]" value="5" >Burgers</li>
</ul>
</ul>
A repo is available: https://github.com/amochohan/CategoryHierarchy which explains in some more detail.
I use this functions to make it work.
//Returns Root elements
public function scopeRoot($query) {
$all = $query->whereParent(0)->get();
$collection = $all->filter(function($single) {
if ($single->ModelFilter('GET')) {
return $single;
}
});
return $collection;
}
//Recursive call
public function traverse() {
self::_traverse($this->Children, $array, $this);
return $array;
}
//This function build a multidimensional array based on a collection of elements
private static function _traverse($collection, &$array, $object) {
$new_array = array();
foreach ($collection as $element) {
self::_traverse($element->Children, $new_array, $element);
}
$array[] = $object;
if (count($new_array) > 0) {
$array[] = $new_array;
}
}
First I get a collection of the root elements those are the ones that I pass to my views where I want to list the tree...
Then I do ...
<ul class="bg-info cat-list">
#foreach($categories as $category)
<?php
$array = $category->traverse();
list_view($array);
?>
#endforeach
</ul>
Using this function...
//Prints a multidimensional array as a nested HTML list
function list_view($element, $ul = true) {
foreach ($element as $value) {
if (!is_array($value)) {
echo "<li>";
echo $value->name;
} else {
echo ($ul) ? "<ul>" : "<ol>";
list_view($valuce, $ul);
echo "</li>";
echo ($ul) ? "</ul>" : "</ol>";
}
}
}
Hope it helps

Zend fetchAll foreach 2 times run dont loop 2nd time;

This is very simple to understand
Image Class
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
public function getList() {
return $this->fetchAll();
}
}?>
My PHP Code
<?php
require 'config.php';
$imgTable = new Image(); // Create Object
$imgList = $imgTable->getList(); // fetch Data
$template = new Template('portfolio'); // Initialize Template and tell which template to pick
$template->imgList = $imgList; // set template variable
$template->render(); // Generate Template output
?>
I can access template variable inside template using $this
Below code is from inside the template
$xback = 0;
foreach ($this->imgList as $images) {
echo 'imageArray[' . $xback . '] = "' . $images['sef'] . '";';
$xback++;
}
?>
.......
<?php
foreach ($this->imgList as $images) {
?>
<div class="portfolio_item">
<img src="<?php echo PATH_WEB . $images['image_thumb'] ?>" height="146" width="209" />
<div class="title"><?php echo $images['image_title'] ?></div>
<div class="right link">
View Details
</div>
</div>
<?php
}
?>
Above code is working fine, but below some few lines, I have to iterate over the same data again dont output any thing. If I comment the first one, 2nd starts working.
First one is to create the JS array and is in head section,
Second part is in HTML to display images
I hope its a pointer issue, I may have to set the loop current item to start, but I am not understanding it right now .... reset($this->imgList) didnt worked
please help
I think it has something to do with the fetchAll call, try this:
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
protected $images;
public function getList() {
// Employ lazy loading pattern to load images if they aren't set yet
if (!isset($this->$images)) {
$this->images = $this->fetchAll();
}
return $this->images;
}
}?>

Categories