Create a multidimensional array by processing the same function over and over - php

I am trying to create a multidimensional array of my navigation. All my pages are created in a CMS and then stored in my DB. Each page will have the usual fields like title, url etc but also they will have a field which tells me if it has any children 'p_has_children' as well as a field which will tell me its parent page 'p_parent' (if it is a child of a page).
I thought I could write a function which I could call and send it an array of all the top level navigation items. Then as I loop through each item I would check if it had any children, get the children (and assign them to an array) and then send them through the same function like so....
function sideNavArray()
{
//Get the side navigation
$getSidenav = $this->crud_model->fetch_rows_where('pages', array('p_side_nav' => 'y', 'p_active' => 'y'));
//Call the navbuilder function
$sidenav = $this->sidenavBuilder($getSidenav, 'navitem', 'nav');
//return the generated nav
return $sidenav;
}
function sidenavBuilder($navItems, $itemClass, $navLevel, $i = 0, $sidenav = array())
{
//Loop over each nav item
foreach($navItems as $navItem){
//For each item I want to add th nav_title, slug, url and page type
$sidenav[$i]['p_nav_title'] = $navItem->p_nav_title;
$sidenav[$i]['p_slug'] = $navItem->p_slug;
$sidenav[$i]['p_url'] = $navItem->p_title;
$sidenav[$i]['p_type'] = $navItem->p_type;
//See if this page has any children
if($navItem->p_has_children == 'y'){
//If the page has children then I want to fetch them from the DB
$subnav = $this->crud_model->fetch_rows_where('pages', array('p_parent' => $navItem->id, 'p_active' => 'y', 'p_protected !=' => 'y'));
if(!empty($subnav)){
//Change the item class and level to subnavitem and subnav
$itemClass = 'sub' . $itemClass;
$navLevel = 'sub' . $navLevel;
//Assign the children to the same array as its parent in the "subnav" level and send it through the sitenavBuilder function
$sidenav[$i][$navLevel] = $this->sitenavBuilder($subnav, $itemClass, $navLevel);
}
}
$i++;
//End foreach loop
}
return $sidenav;
}
I am sure some of you are looking at this right now and saying well of course that won't work!
I currently have a navigation being generated but it is on the front end and every time I want to add an additional level I have to go into the code and add it manually. I want to avoid having to write each level of the navigation as I want it to be able to grow to as many levels as it can without me having to go in and code that extra level if it is needed every time.
I hope this all makes sense. Basically I want to know if there is a way to get this nav array to be built by running through the same loop over and over until it doesn't need to anymore.

Related

How to delete item ID from array used as session shopping cart

I have a SESSION['cart'] with ID numbers only. I have a form passing the ID with a remove button. Once passed to my controller, I cannot figure out how to write the code that uses the ID ($_POST['id']) to delete the item from the SESSION['cart'].
I can loop through and display the array contents, but I cannot figure out how to delete based on ID passed from the form.
How do I loop through the SESSION['cart'] array to find a match with the ID passed from my delete form, and then delete that ID? I know that unset($_SESSION['cart'][X] deletes the ID at index X, but I cannot figure out how to loop through all the elements to find a match.
I have read a number of related issues in this forum but have been unable to apply any of those solutions to resolve this challenge. Any assistance is appreciated.
The way you have your values ($products = array(3,7,99,152)) isn't a very good method. Every time you want to perform an action, you have to loop through the array, you don't want that. Apart from that, how do you store quantity? Or variations like e.g. size or color?
if your structure is $array[ ID_OF_PRODUCT ], you can simply do this:
unset( $_SESSION['cart'][$_POST['id']] ); // Instant access via the key!
This should be the method to use. This allows you to create an array like this, with advanced info, but with easy access (42/63 are example id's)
$_SESSION['cart']['products'][42] = array(
'quantity' = 11,
'size' = 'large',
'color' = 'blue'
);
$_SESSION['cart']['products'][63] = array(
'quantity' = 9,
'size' = 'small',
'color' = 'red'
);
This way you can access a lot of info with the product ID, and now also see which size and color (both just examples) the user selected. You may not have need for this now, but you will further down the road :)
As you might see, you can easily do stuff with the item:
isset($_SESSION['cart'][$_POST['id']]); // check if the product exists
unset($_SESSION['cart'][$_POST['id']]); // remove the product
echo $_SESSION['cart'][$_POST['id']]['quantity']; // get the quantity.
Not a loop in the code. You should only use loops when you have to, try to somewhat avoid them because often their slow. Say you have an extreme case of 1000 items in your shop, and you need to delete no999... That'll take a noticable moment.
Here is the code to do it right:
$id = $_POST['id'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
$_SESSION["cart"] = array_values($items);
Advice
Beside item ID, you can also sve item count in SESSION array because user can add several times same item into cart. In that case your $_SESSION["card"] should be structured like:
array(
'1'=>12,//Item with ID=1 is added 12 times in shopping cart
'17'=>2,//Item with ID=17 is added 2 times in shopping cart etc.
'32'=>12,
)

PHP & Mysql tree navigation menu with unlimited sub categories

Im looking for a way to extract the data from the mysql database to create an unlimited subcategry menu.
The menu has about 1500 categories in it and they are stored into the database table (menu) in the following format :
category_id , category title , parent_id
i want to do 1 mysql query to put all the data into an array.
$menu_list =array();
$query = mysql_query("SELECT * FROM menu ORDER BY category_id ASC");
if(mysql_num_rows($query) != 0) {
while($row = mysql_fetch_array($query)){
$category_id = $row['category_id'];
$title = $row['category_title'];
$parent_id = $row[parent_id'];
$menu_list[] = array($category_id,$title,$parent_id);
}
}
That is the code that i am currently using to turn the data into the array.
I then need to loop through the array to build a menu up.
I will then hide all subcategories and expand with jquery ( I can do this bit no problem )
The problem i have is going through the array and displaying the data in the right order.
The menu has unlimited subcategories so it will probably need to be a recursive function to retrieve the data.
I have folllowed alot of the examples on here but then i get lost how to display the data..
i now need to end up with :
main item
sub cat
sub cat
sub cat
sub cat
main item
sub cat
main item
main item
sub cat
sub cat
sub cat
sub cat
sub cat
etc...
with each category in its own div
I will then need to be able to edit each category (ie title name and position if need be)
then if i change where a sub category is based a quick page refresh will reload the menu in the new order..
eventually i would like to make this into a drag and drop but that will be at a later date.
I hope this has explained it enough..
Thanks in advance..
So the problem has come back to haunt me again...
My method of ajax calling another mysql select was ok for the CMS section as it was only used from time to time.
But now we have got to the front end.
Each time the page is viewed the first 3 levels of the menu are pulled using numerous mysql requests.
As the categories are getting bigger this is now resulting in 1600+ categories being pulled numerous times each, and even at 1000 visits a day will result in more than a 1000000 sql requests a day.
So i think i will definately need to pull the categories into an array, and then recursively go through the array.
I have looked at the solutions above and they seem to work on paper but not in practise.
If anyone can attempt to give me another solution it would be appreciated..
just to recap in my db i have : id , category_name , parent_id
I am now using PDO with mysql and prepared statements for added security..
Thanks in advance..
Here is the code what you need
category_id AS id , category title AS kategori and parent_id AS kid
function countsubcat($pid)
{
$r=mysql_query("select count(kid) AS say from meskat where kid='$pid' limit 1");
$rw=mysql_fetch_array($r);
return $rw['say'];
}
function listmenu($pid = 0)
{
$res = mysql_query("select id,kategori,kid from meskat where kid='$pid'");
while($cat=mysql_fetch_array($res))
{
echo '<li>';
print''.$cat['kategori'].'';
if(countsubcat($cat['id'])>0)
{
print'<ul>';
listmenu($cat['id']);
print'</ul>';
}
echo '</li>';
}
}
echo '<ul>';
listmenu(0); //starting from base category
echo '</ul>';`
In MySQL, this will require many queries, one for each level plus one at a minimum.
you grab all the top-level categories, use them as root nodes for a forest (a group of trees).
You grab all of the categories that are children of any of them.
Add each of these categories as children to the parent node
If there are still children, go to step two, otherwise stop.
What you end up with a tree that you do a depth-first walk through to convert to some (presumably) html representation (e.g. nested lists).
There are some optimisations you can perform. If you sort the child levels by parent ID, then you can assume continuous blocks of children, meaning you don't have to do as many lookups to find the correct parent, just check for a parent id change.
If you maintain a list of the current lowest level of categories, indexed by ID, you can speed up forest creation.
If you overlap steps 2 and 4, then you only do n+1 queries (where n is the number of levels), so checking for more children is also grabbing the next level of children.
In terms of memory, this will use the memory required for the tree, plus lowest level lookup table and a current parent id.
The building algorithm it fairly fast, scaling linearly with the number of categories.
This method also successfully avoids corrupted sections of data, because it won't grab data that have cycles (no root node).
I also suggest using a prepared statement for the children query, since MySQL will compile and cache the query, it will speed up the operation by only sending new data across the wire.
If you don't understand some of the concepts, I suggest hitting up Wikipedia as I have tried to use standard terms for these.
Can you alter the table structure? In that case you could take a look at the Nested Set Model (link includes description and implementation details, scroll down to The Nested Set Model). Node insertion and removal becomes more complex, but allows you to retrieve the whole tree in just one query.
If you can assume that for any category category_id > parent_id is true, the following recursive functions to represent the menu as a multi-level array and render it as a nested HTML list would work:
$menu = array();
$query = mysql_query("SELECT category_id, category_title, parent_id FROM menu ORDER BY category_id ASC");
if(mysql_num_rows($query) != 0) {
while($row = mysql_fetch_assoc($query)) {
if(is_null($row['parent_id']))
$menu['children'][] = $row;
else
add_to_menu(&$menu,$row);
}
}
function add_to_menu($menu,$item) {
if(isset($menu['children'])) {
foreach($menu['children'] as &$child) {
if($item['parent_id'] == $child['category_id']) {
$child['children'][] = $item;
} else {
add_to_menu(&$child,$item);
}
}
}
}
function render_menu($menu) {
if(isset($menu['children'])) {
echo '<ul>';
foreach($menu['children'] as &$child) {
echo "<li>";
echo $child['category_id']." : ".$child['category_title'];
if(isset($child['children'])) {
render_menu(&$child);
}
echo "</li>";
}
echo '</ul>';
}
}
render_menu($menu);
So after various attempts at different solutions i actually have used jquery and a ajax load to retreive the next level.
With mine main categories all have a parent of 1 - shop i do a mysql scan for all categories with 1 as the parent id.
This will then display the main categories. Attached to each main category i have added a folder icon if they have any sub categories.
I have also inserted a blank div with an id of that category.
When the folder is clicked it does an ajax call to a php script to find all categories with that parent. These are appended to the parents_id div.
This inturn adds the category (with a css padding to indicate a sub category) and again a folder sign if it has sub categories as well as another blank div with the category_id.
You can continue this for as many categories and sub categories as the client requires.
I took it a stage further and added an edit icon to category/subcategory so categories can be moved or changed.
If you would like some sample code for this let me know...
Actually, you need very little code to build a tree.
You also only need one query.
Here is what I came up with (I use Drupal's database but it is explicit enough to understand):
$items = db_select('menu_items', 'mi')
->fields('mi')
->orderBy('position')
->execute()
->fetchAllAssoc('id', PDO::FETCH_ASSOC);
// Example of result. The ID as key is important for this to work.
$items = array(
3 => array('id' => 3, 'parent' => NULL, 'title' => 'Root', 'position' => 0),
4 => array('id' => 4, 'parent' => 3, 'title' => 'Sub', 'position' => 0),
5 => array('id' => 5, 'parent' => 4, 'title' => 'Sub sub', 'position' => 0),
6 => array('id' => 6, 'parent' => 4, 'title' => 'Sub sub', 'position' => 1),
);
// Create the nested structure. Note the & in front of $item.
foreach($items as &$item)
if($item['parent'])
$items[$item['parent']]['sub items'][$item['mid']] =& $item;
// Now remove the children from the root
foreach($items as $id => $item)
if($item['parent']) // This is a child
unset($items[$id])
At this point, all you need is a recursive function to display the menu:
function print_menu($items) {
echo '<ul>';
foreach($items as $item) {
echo '<li>';
echo '' . $item['title'] . '';
if(!empty($item['sub items']))
print_menu($item['sub items']);
echo '</li>';
}
echo '</ul>';
}

Create a Dynamic Nav on the Fly

I'm looking for the best way to create a complex navigation element on the fly. I have all of the elements in a database (title, id, parentId) and I want to efficiently take them out of the DB and display them correctly. I also want to collapse all of the navigation elements that aren't active. So if I was browsing through "Sofas" I wouldn't see "Chandeliers" or any of the categories under lighting but I would see "Lighting".
This is what I want the final product to look like:
Furniture
Living Room
Sofas
Chairs
Ottomans
Bedroom
Beds
Nightstands
Lighting
Chandeliers
Floor Lamps
Sconces
Rugs & Textiles
Contemporary
Vintage
My current method is
write one SQL query that pulls down all of the category names, ids, and parent ids
Iterate through the categories and put into a sorted multi-dimensional array with child categories stored under their parents.
Iterate through the new array and add another entry to mark the appropriate categories as open (all categories are closed by default)
iterate through the array and write HTML
I'm trying to to this with as few interations as possible and I'm sure the code I have right now is inefficient. Especially step 2 I iterate through the array several times. There has to be a general solution to this (common?) problem.
Consider adding a new field to your database table: level.
Main-categories will have level 0.
Sub-categories will have level 1.
Sub-sub-categories will have level 2.
etc.
This trick will help you to know which sub-categories to disable without 2nd iteration of the array.
I believe this is the perfect place to generate your html code using recursion.
I used this function a while ago. It is working with a multi-dimensional array (tree)
function buildMenu($menu_array, $is_sub=FALSE) {
$attr = (!$is_sub) ? 'id="menu"' : 'class="submenu"';
$menu = "<ul $attr>\n";
foreach($menu_array as $id => $elements) {
foreach($elements as $key => $val) {
if(is_array($val)) {
$sub = buildMenu($val, TRUE);
}
else {
$sub = NULL;
$$key = $val;
}
}
if(!isset($url)) {
$url = $id;
}
$menu .= "<li>$display$sub</li>\n";
unset($url, $display, $sub);
}
return $menu . "</ul>\n";
}
echo buildMenu($menu_array);
This adds css properties too. If you wish to mark the currently active page you can use the strpos() function to find your current url. If you need some more functionality you can easily add them to buildMenu()
Using level as mentioned in the answer above will help too. If you were using the nested set model in your database I could also help you with my query which is a single select returning the whole menu data.

post rating for an individual item in a list using codeigniter

I’m having a heck of a time figuring out how to post a rating for an individual item in a list of items,
this code let’s me rate multiple items, but not single items:
for($i=0;$i<2;$i++){
$doc_item_id = $_POST['item_id0'][$i];
$doc_rating = $_POST['document_rating'][$i];
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
}
whereas this code let’s me rate only the first item (or last item depending on where i put the "break;"):
foreach($_POST['item_id0'] as $doc_item_id){
foreach($_POST['document_rating'] as $doc_rating){
}
break;
}
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
any thoughts on how to correct either of these such that the user could rate the individual item of their choosing would be greatly appreciated,
If the user is supposed to choose the item to rate (instead of rating all items at the same time), you should allow him to do so (showing only one item, let him select one using radio buttons...), and then you should be able, by PHP side, to retrieve the index of the item to modify.
Finally, in order to modify only one item, your code should look like (PHP side, you will certainly have to update your HTML form as well)
$i = $_POST['item_index']; // Here I'm supposing that you have added radio buttons
// named 'item_index' to allow user to choose the item to rate
$doc_item_id = $_POST['item_id0'][$i];
$doc_rating = $_POST['document_rating'][$i] ;
$it_rt = array(
'item_id'=> $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
In fact it would be nearly your original code without the for loop.
Looping through the entire list just to limit the item you want, is kinda bad.
Here's an example on how to do it using some array functions:
$last=true; // false for first
if($last){
$id=end($_POST['item_id0']);
}else{
$id=reset($_POST['item_id0']);
}
// alternative: $id=($last)?end($_POST['item_id0']):reset($_POST['item_id0']);
// test id
if($id===false){
// no item was supplied
}
if(!isset($_POST['document_rating'][$id])){
// somehow, the item id doesn't have a matching document rating
}
// everything is okay!
$doc_item_id = $_POST['item_id0'][$id];
$doc_rating = $_POST['document_rating'][$id];
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);

PHP: Session 2-Dimensional Array - Track Viewed Products

I'm trying to create an array to display the last 5 products a customer has viewed.
The array is a 2 dimensional array like below...
$RView= array(
array( ID => "1001", RefCode => "Ref_01", Name => "Name_01" ),
...
array( ID => "1005", RefCode => "Ref_05", Name => "Name_05" )
);
The array values are retrieved from the products recordset and is designed to function as follows when a customer visits a product page.
Page will check if a Session Array exists
If yes, an array variable is created from existing Session
If no, a new array is created.
Array will add the new product details.
Array will count if there are more than 5 existing products in the array.
If yes, it will remove the oldest.
If no, moves to next step.
A Session is created/updated from the revised Array.
My current effort is attached below...
Many thanks for any help.
<?php
session_start()
// Get or Create Array
IF (isset($_SESSION['sessRView'])) {
$RView = ($_SESSION['sessRView']); }
ELSE {
$RView = array(array());
}
// Append currently viewed Product to Array
array(array_unshift($RView, $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name']));
// Check if more than 5 products exist in Array, if so delete.
IF (sizeof($RView) > 5) {
array(array_pop($RView)); }
// Update Session for next page
$_SESSION['sessRView'] = $RView;
// Display Array
for ($row = 0; $row < 5; $row++)
{
echo "<ul>";
echo "<li><a href='?PrdID=".$RView[$row]["PrdID"]."'>".$RView[$row]["RefCode"]."</a> : ".$RView[$row]["Name"]."</li>";
echo "</ul>";
}
?>
It's more or less right - just 2 lines need to be changed.
There's no need for the extra array() around array_unshift and array_pop.
When you use array_unshift you're pushing an array of items (not the id/codes individually) - I think you mean array_unshift($RView, array($prodid,$name,...))
What if $RView doesn't have 5 elements? In that case you're accessing undefined array indices (which may or may not show an error). Change it to a foreach loop: e.g.
foreach ($Rview as $prod) echo $prod['Name']...
It should work after you make these changes. You might want to clean up the coding style a bit, though :)
EDIT: Oh, I see, when you're referencing the array in the for loop it doesn't know that the array has "ProdID" and "Name" indices. When you make an array you have to define the indexes using the => operator.
Add indexes to the array when you array_unshift:
array_unshift($RView, array("ProdID" => $row_rsProd["ProdID"], "Name"...))
If row_rsProd isn't too big, you can just tack the entire row_rsprod onto $RView.
so change array_unshift(...) to just $RView[] = $row_rsProd
This way the indexes are preserved.
Alternatively you can change the indicies in the for loop to match. Right now the array you unshift onto $RView is 0-based - $RView[0][0] is the product ID for the first product, etc.
So you can change the stuff in the foreach loop to
echo "<li>..." $prod[0] $prod[1] $prod[2]
Hope that helps!

Categories