Jump to content

[SOLVED] sorting and comparing multi-dimensional arrays. need help.


boo_lolly
Go to solution Solved by boo_lolly,

Recommended Posts

a little background:

i'm building a pseudo-shopping cart for a client of mine. i say 'pseudo' because there is no database or cms backend for this system. all the items will be hard-coded in HTML forms. the shopping cart items will be stored entirely in a session as any normal shopping cart handles them.

 

each item will have a few pre-defined values such as id, price, name, quantity, and an array called ingredients. for example, let's say one of the item's is a sandwitch. the sandwitch comes standard with lettuce, tomatoes, and cheese. these options will be the pre-checked options in the sandwitch form. however, the user can uncheck these options, and check other options such as 'mayonaise' or 'pickles' for example. so imagine these variables are stored in hidden input fields for the sandwitch form:

Code:

 

$id = 1;

$name = 'sandwitch';

$price = 6.50;

$quantity = 1;

$itemInfo = array('23' => 'lettuce', '12' => 'tomatoes', '43' => 'mayonaise');

 

 

now here's where it gets confusing for me... i need to write a function to check all the items of the shopping cart to FIRST see if there is a repeat of the same item in the shopping cart (for instance if the user added the sandwitch twice), THEN if there is more than one of the same item in the shopping cart, compare their ingredients array to see if they are the same... if they are, don't add the posted item into a new index in the shopping_cart array, instead add 1 to the quantity of the existing identical item.

 

the reason why i need this is because there shouldn't be 2 separate sandwitches listed in the shopping cart, if they are the same sandwitch. it should only have one entry, and show a quantity of 2. but the user can add 2 sandwitches, but have different things on the sandwitch, in which case there would be 2 separate sandwitches in the cart and their contents listed below each one.

 

does that make sense? if there is any more information you guys need to know, just let me know. i'll do my best to explain the situation as detailed as possible so i can be led in the right direction.

 

the contents of the cart will be stored in this manner:

$_SESSION['cart']
   |
   +----[item1]
   |   |
   |   +-----[id] = 1
   |   |
   |   +-----[name] = 'sandwitch'
   |   |
   |   +-----[price] = 6.50
   |   |
   |   +-----[quantity] = 1
   |   |
   |   +-----[ingredients]
   |         |
   |         +-----[lettuce]
   |         |
   |         +-----[tomatoes]
   |         |
   |         +-----[cheese]
   |
   +----[item2]
   |   |
   |   +-----[id] = 1
   |   |
   |   +-----[name] = 'sandwitch'
   |   |
   |   +-----[price] = 6.50
   |   |
   |   +-----[quantity] = 1
   |   |
   |   +-----[ingredients]
   |         |
   |         +-----[lettuce]
   |         |
   |         +-----[tomatoes]
   |         |
   |         +-----[cheese]
   |         |
   |         +-----[mayonaise]
   |
   +----[item3]
      |
      +-----[id] = 1
      |
      +-----[name] = 'sandwitch'
      |
      +-----[price] = 6.50
      |
      +-----[quantity] = 1
      |
      +-----[ingredients]
            |
            +-----[lettuce]
            |
            +-----[mustard]
            |
            +-----[cheese]

 

but if there are two sandwitches with the same exact itemInfo:

 

$_SESSION['cart']
   |
   +----[item1]
   |   |
   |   +-----[id] = 1
   |   |
   |   +-----[name] = 'sandwitch'
   |   |
   |   +-----[price] = 6.50
   |   |
   |   +-----[quantity] = 2
   |   |
   |   +-----[ingredients]
   |         |
   |         +-----[lettuce]
   |         |
   |         +-----[tomatoes]
   |         |
   |         +-----[cheese]
   |
   +----[item2]
      |
      +-----[id] = 1
      |
      +-----[name] = 'sandwitch'
      |
      +-----[price] = 6.50
      |
      +-----[quantity] = 1
      |
      +-----[ingredients]
            |
            +-----[lettuce]
            |
            +-----[tomatoes]
            |
            +-----[cheese]
            |
            +-----[pickles]

 

 

here is my itemTemplate.php:

<?php
        session_start();

        /*if this is the first page the user sees, register the session id now*/
        if(!isset($_SESSION['session_id']) || empty($_SESSION['session_id'])){ $_SESSION['session_id'] = session_id(); }

        function populateForm($name, $id, $price, $quantity, $standard_ingredients, $all_ingredients){
                echo "
                        <b>{$name}</b>
                        <form action=\"cart.php\" method=\"post\">
                        <input type=\"hidden\" name=\"id\" value=\"{$id}\">
                        <input type=\"hidden\" name=\"name\" value=\"{$name}\">
                        <input type=\"hidden\" name=\"price\" value=\"{$price}\">
                        <input type=\"hidden\" name=\"quantity\" value=\"{$quantity}\">
                \n";

                foreach($all_ingredients as $a_ingredient){
                        echo "\t\t\t<input type=\"checkbox\" name=\"ingredients[]\" value=\"{$a_ingredient}\"";
                                foreach($standard_ingredients as $s_ingredient){
                                        (($s_ingredient == $a_ingredient) ? (" CHECKED") : (""));
                                }
                        echo ">{$a_ingredient}\n";
                }

                echo "
                        <br /><b>$". number_format($price, 2) ."</b>
                        <br /><input type=\"submit\" value=\"Add to Cart\">
                        </form>
                \n";
        }

        /* set standard ingredients array*/
        $all_sandwich_ingredients = array('mustard', 'mayonnaise', 'pickles',
                                          'lettuce', 'tomatoes', 'cheese');
        /* set all possible ingredients array*/
        $standard_sandwich_ingredients = array('lettuce', 'tomatoes', 'cheese');

        /*execute form*/
        populateForm('Sandwich', 12, 6.50, 1, $standard_sandwich_ingredients, $all_sandwich_ingredients);
?>

 

and here is my cart.php

<?php
        session_start();
        session_destroy();

        /*if this is the first page the user sees, register the session id now*/
        if(!isset($_SESSION['session_id']) || empty($_SESSION['session_id'])){ $_SESSION['session_id'] = session_id(); }

        /*print $_SESSION data*/
        echo "<b>SESSION ARRAY:</b>\n<pre>\n"; print_r($_SESSION); echo "</pre>\n";

        /*print $_POST data*/
        echo "<b>POST ARRAY:</b>\n<pre>\n"; print_r($_POST); echo "</pre>\n";

       /*
        * if the user is sent to this page from submiting an item
        * if the shopping cart is empty, there are no items to
        * compare with. so, it won't proceed, it will just add
        * it as the first submitted item to the cart. if there
        * are items in the cart, we will assume that the $_POSTed
        * item is not identical to any items in the cart. now,
        * we run through each item in the cart one by one. we
        * first compare the id's of the shopping cart item that
        * is being evaluated and the item that was $_POSTed. if
        * the id's do match, sort their item attributes. then,
        * compare the arrays. if the attributes match, do not add
        * the $_POSTed item into a new index in the cart array,
        * just add the quantity of the $_POSTed item to the
        * existing identical item already in the cart. if
        * the items are not identical, add the $_POSTed item
        * into a new index in the cart array. unset the $_POST
        * array so if the user 'refreshes' the page, it will not
        * add the item again.
        */
        if(isset($_POST)){
                echo "\$_POST isset<br />\n";
                if(!empty($_SESSION['shopping_cart'])){
                        echo "shopping cart is not empty<br />\n";
                        foreach($_SESSION['shopping_cart'] as $key => $cart_item){
                                if($cart_item['id'] == $_POST['id']){
                                        echo "item already exists<br />\n";
                                        if(sort($_POST['ingredients'], SORT_STRING) == sort($cart_item['ingredients'], SORT_STRING)){
                                                echo "item is identical. add to quantity<br />\n";
                                                $cart_item['quantity'] += $_POST['quantity'];
                                        }else{ $_SESSION['shopping_cart'][] = $_POST; echo "add a new item to the cart because items are not identical<br />\n"; }
                                }
                        }
                }else{ $_SESSION['shopping_cart'][] = $_POST; echo "add a new item to the cart because cart is empty<br />\n"; }
                foreach($_POST as $key => $val){ unset($key); }
        }
?>

 

 

issues i am having with this code:

itemTemplate.php : item attributes will not pre-check themselves.

 

cart.php : items will not be added to the cart, no matter what i try.

 

cart.php : unset($_POST) will not unset the array.

 

 

this is what cart.php prints after submitting one item from itemTemplate.php:

SESSION ARRAY:

Array
(
    [session_id] => 
)

POST ARRAY:

Array
(
    [id] => 12
    [name] => Sandwich
    [price] => 6.5
    [quantity] => 1
    [ingredients] => Array
        (
            [0] => mustard
            [1] => mayonnaise
            [2] => tomatoes
        )

)

$_POST isset
add a new item to the cart because cart is empty

 

somebody please help me get this! this should be a very simple task but for some reason it has eluded me! please help. thanks.

Link to comment
Share on other sites

the post above illustrates what cart.php shows after an item has been submitted. then, if you refresh your browser, it prints this:

SESSION ARRAY:

Array
(
    [session_id] => 0e89d0ac179eb36cc3592baa1ffdfe67
    [shopping_cart] => Array
        (
            [0] => Array
                (
                    [id] => 12
                    [name] => Sandwich
                    [price] => 6.5
                    [quantity] => 1
                    [ingredients] => Array
                        (
                            [0] => mustard
                            [1] => mayonnaise
                            [2] => tomatoes
                        )

                )

        )

)

POST ARRAY:

Array
(
    [id] => 12
    [name] => Sandwich
    [price] => 6.5
    [quantity] => 1
    [ingredients] => Array
        (
            [0] => mustard
            [1] => mayonnaise
            [2] => tomatoes
        )

)

$_POST isset
shopping cart is not empty
item already exists
item is identical. add to quantity

 

sooooo.... it's functional to a certain extent.... right? what's the deal? why isn't $_POST unsetting?

Link to comment
Share on other sites

Come on now =)

 

foreach($_POST as $key => $val){ unset($_POST[$key]); }

 

You gotta unset the index like I posted to you before =)

 

I guess on that note it doesn't seem like any of that code i did for ya passed your test...?

Link to comment
Share on other sites

hey frost =), nah unfortunately i spent a lot time working out the errors trying to get it to work. and i didn't really understand it to begin with, but i think there was a lack of communication on my part. i guess my code isn't as functional as i thought before, because when i re-tested the cart handler, i get these results:

SESSION ARRAY:

Array
(
    [session_id] => 0e89d0ac179eb36cc3592baa1ffdfe67
    [shopping_cart] => Array
        (
            [0] => Array
                (
                    [id] => 12
                    [name] => Sandwich
                    [price] => 6.5
                    [quantity] => 1
                    [ingredients] => Array
                        (
                            [0] => mayonnaise
                            [1] => tomatoes
                        )

                )

        )

)

POST ARRAY:

Array
(
    [id] => 12
    [name] => Sandwich
    [price] => 6.5
    [quantity] => 1
    [ingredients] => Array
        (
            [0] => pickles
            [1] => lettuce
            [2] => tomatoes
            [3] => cheese
        )

)

$_POST isset
shopping cart is not empty
item already exists
item is identical. add to quantity

 

obviously the items are not identical. so there's a problem with this line:

if(sort($_POST['ingredients'], SORT_STRING) == sort($cart_item['ingredients'], SORT_STRING)){

 

 

i thought i was unsetting the index with

foreach($_POST as $key => $val){ unset($_POST[$key]); }

 

that's the code you gave me =) but for some reason it won't unset. thanks for all your help so far frost.

Link to comment
Share on other sites

Let me ask you this, why does it need to be unset in the first place?

 

As for the code I made you, I will try and test it out and see what happens tonight.

 

But yea that sorting if statement I wouldn't trust at all.

 

<?php 
$_SESSION = array("shopping_cart" => array(12 => array(0 => array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes")))));
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes"));

addItem();
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes", "pickles"));
addItem();

function addItem() {
$add = false; 
if (isset($_POST) && isset($_SESSION['shopping_cart'])) { 
      if (is_array($_SESSION['shopping_cart'])) { 	
           if (isset($_SESSION['shopping_cart'][$_POST['id']])) { 
			$x=0;
                foreach ($_SESSION['shopping_cart'][$_POST['id']] as $key => $items) { 
				 $i=0; 
                     $unique=false; 
                     foreach ($items as $item => $val) { 

					if ($item != "quantity") { 
                            if (is_array($val)) {
							$result = array_diff($val, $_POST[$item]);
							$result2 = array_diff($_POST[$item], $val);

							if (count($result) > 0 || count($result2) > 0) {
								$unique = true;
								break;
							}
						}							

						$i++; 
                            if (!isset($_POST[$item])) { 
                                $unique = true; 
                                break; 
                            }elseif ($_POST[$item] === $val) { 
                                continue; 
                            }else { 
                                $unique = true; 
                                break; 
                            } 
                          } 
                     } 
                      
                     if ($unique) { 
                          break; 
                     } 
                     $unique = false;
				 $x++;
                } 
                 print ($unique)?"true":"false";
                if ($unique)  
				$_SESSION['shopping_cart'][$_POST['id']][(count($_SESSION['shopping_cart'][$_POST['id']]))] = $_POST;
                else 
                    $_SESSION['shopping_cart'][$_POST['id']][($x - 1)]['quantity']++; 
           }else { 
                $add = true; 
           } 
      }else { 
           $add = true; 
      } 
       
      if ($add) 
           $_SESSION['shopping_cart'][$_POST['id']][0] = $_POST; // set the item id to the post 
       
      foreach ($_POST as $key => $val) 
           unset($_POST[$key]); 
	   
  print_r($_SESSION);
} 
}

  print_r($_POST);

?>

 

That will work like you want it to.

Link to comment
Share on other sites

unfortunately frost, it does not do what i want it to do =\. it won't add any items to the session cart no matter what i try. ontop of that, the code checks to see if it comes across an array in one of the indexes of the cart item, and then compares the ingredients. however, if a user enters a sandwitch with no ingredients, it doesn't store that index as an array in the $_POST index. i really don't know what to do.... it's somewhat difficult to follow. can you explain the logic stepbystep?

 

<?php
        function addItem(){
                $add = false;
                if(isset($_POST) && isset($_SESSION['shopping_cart'])){
                        if(is_array($_SESSION['shopping_cart'])){
                                if(isset($_SESSION['shopping_cart'][$_POST['id']])){
                                        $x=0;
                                        foreach($_SESSION['shopping_cart'][$_POST['id']] as $key => $items){
                                                $i = 0;
                                                $unique = false;
                                                foreach($items as $item => $val){
                                                        if($item != "quantity"){
                                                                if(is_array($val)){
                                                                        $result = array_diff($val, $_POST[$item]);
                                                                        $result2 = array_diff($_POST[$item], $val);
                                                                        if(count($result) > 0 || count($result2) > 0){
                                                                                $unique = true;
                                                                                break;
                                                                        }
                                                                }
                                                                $i++;
                                                                if(!isset($_POST[$item])){
                                                                        $unique = true;
                                                                        break;
                                                                }
                                                        }elseif($_POST[$item] === $val){
                                                                continue;
                                                        }else{
                                                                $unique = true;
                                                                break;
                                                        }
                                                }
                                        }
                                        if($unique){ break; }
                                        $unique = false;
                                        $x++;
                                }
                                print ($unique) ? "true" : "false";
                                if($unique){
                                        $_SESSION['shopping_cart'][$_POST['id']][(count($_SESSION['shopping_cart'][$_POST['id']]))] = $_POST;
                                }else{
                                        $_SESSION['shopping_cart'][$_POST['id']][($x - 1)]['quantity']++;
                                }
                        }else{
                                $add = true;
                        }
                }else{
                        $add = true;
                }
                if($add){
                        $_SESSION['shopping_cart'][$_POST['id']][0] = $_POST; // set the item id to the post
                        foreach($_POST as $key => $val){ unset($_POST[$key]); }
                }
        }
?>

 

this is what it prints upon submitting an item:

SESSION ARRAY:

Array
(
    [session_id] => 299c29cfa3ed5119f8b383455de1117d
    [shopping_cart] => Array
        (
            [12] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => Sandwich
                            [price] => 6.5
                            [quantity] => 1
                            [ingredients] => Array
                                (
                                    [0] => mustard
                                    [1] => pickles
                                    [2] => tomatoes
                                )

                        )

                )

        )

)

POST ARRAY:

Array
(
    [id] => 12
    [name] => Sandwich
    [price] => 6.5
    [quantity] => 1
    [ingredients] => Array
        (
            [0] => mustard
            [1] => mayonnaise
        )

)


Fatal error: Cannot break/continue 1 level in cart.php on line 85

 

line 85 is this little guy:

if($unique){ break; }

 

it won't add anymore than one item to the cart. after one item goes in, you can't do anything else. for some reason this seems like way too much code to be efficient. and my code looks way to short to function properly. i'm going to see if i can adopt some of your logic and apply it to my code.

Link to comment
Share on other sites

Alright man here it is with comments. I added a new check for the "is_null" on the array_diff as if there is not an array that should return null.

 

<?php
function addItem(){
// use this variable to determine if we just add it to the array
$add = false;
// make sure we have data to work with
if(isset($_POST) && isset($_SESSION['shopping_cart'])){
	// Make sure the shopping cart is present
	if(is_array($_SESSION['shopping_cart'])){
	// Check and see if we have a similiar item in the shopping cart already
	if(isset($_SESSION['shopping_cart'][$_POST['id']])){
		$x=0;
		// We do, let's go through each item and do a comparison
		foreach($_SESSION['shopping_cart'][$_POST['id']] as $key => $items){
			$i = 0;
			$unique = false;
			// Ok looping through each item to take a look at their descriptions and compare
			foreach($items as $item => $val){
				// Since quantity can be different we do not want to check it
				if($item != "quantity"){
					// If the variable is an array (meaning it is ingredients) than lets do a check
					if(is_array($val)){
						// Do 2 different tests with array_diff on the item ingredients
						$result = array_diff($val, $_POST[$item]);
						$result2 = array_diff($_POST[$item], $val);

						// Since the array_diff returns null if no array is supplied 
						// make sure that if one is null and not the other that we show it is unique
						if (is_null($result) || is_null($result2)) {
							$unique = true;
							break;
						// elseif none of them are null let's compare the counts of the arrays. 
						}elseif(count($result) > 0 || count($result2) > 0){
							$unique = true;
							break;
						}

						// If the counts are greater than zero than it means there was a difference in the arrays!
					}

					$i++;
					// Check to make sure that the index of $item is set in post
					// if it is not than this is obviously unique
					if(!isset($_POST[$item])){
						$unique = true;
						break;
					// Ok the value is set check to see that the type and values are the same
					}elseif ($_POST[$item] === $val) {
						continue;
					// If they are not the same than this is obviously a unique entry!
					}else {
						$unique = true;
						break;
					}
				}
			}

			// If the entry is shown as unique break the main for each!
			if($unique){ break; }
				$unique = false;
				$x++;
			}
		}

		// If it is unique than we want to add a new item to the array at shopping_cart::item::index + 1 ($x) should show the index.
		if($unique){
			$_SESSION['shopping_cart'][$_POST['id']][(count($_SESSION['shopping_cart'][$_POST['id']]))] = $_POST;
		}else{
			// else it is not unique so just total quantity of shopping_cart::item::index
			$_SESSION['shopping_cart'][$_POST['id']][($x - 1)]['quantity']++;
		}
	}else{
		// Else we are just adding the item to the array
		$add = true;
	}
}else{
	$add = true;
}

// If we are just adding the item lets add the new item in shopping_cart::itemid::index 0 
if($add){
	$_SESSION['shopping_cart'][$_POST['id']][0] = $_POST; // set the item id to the post
}

// lets unset the post data for some reason?
foreach($_POST as $key => $val){ unset($_POST[$key]); }
}
?>

 

As for it not working, for a portion meaning that passing one without an array of ingredients this should solve that (untested) but yea.

 

Either way this should work:

 

EDIT:

Fixed the tab problem.

 

EDIT:

Found a new problem, working on it.

Link to comment
Share on other sites

Posting a new post as the code changed dramatically.

 

This should work exactly as desired.

<?php
print "<pre>";
$_SESSION = array("shopping_cart" => array(12 => array(0 => array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes")))));
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes"));

addItem();
print_r($_SESSION);
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes", "pickles"));
addItem();
print_r($_SESSION);
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array("mayonnaise", "tomatoes", "pickles"));
addItem();
print_r($_SESSION);
$_POST = array("id" => 12, "name" => "Sandwhich", "price" => 6.5, "quantity" => 1, "ingredients" => array());
addItem();
print_r($_SESSION);
function addItem(){
// use this variable to determine if we just add it to the array
$add = false;
// make sure we have data to work with
if(isset($_POST) && isset($_SESSION['shopping_cart'])){
	// Make sure the shopping cart is present
	if(is_array($_SESSION['shopping_cart'])){
		// Check and see if we have a similiar item in the shopping cart already
		if(isset($_SESSION['shopping_cart'][$_POST['id']])){
			$x=0;
			// We do, let's go through each item and do a comparison
			foreach($_SESSION['shopping_cart'][$_POST['id']] as $key => $items){
				$i = 0;
				$unique[$x] = false;
				// Ok looping through each item to take a look at their descriptions and compare
				foreach($items as $item => $val){
					// Since quantity can be different we do not want to check it
					if($item != "quantity"){
						// If the variable is an array (meaning it is ingredients) than lets do a check
						if(is_array($val)){

							// Do 2 different tests with array_diff on the item ingredients
							$result = array_diff($val, $_POST[$item]);
							$result2 = array_diff($_POST[$item], $val);

							// Since the array_diff returns null if no array is supplied 
							// make sure that if one is null and not the other that we show it is unique
							if (is_null($result) xor is_null($result2)) {
								$unique[$x] = true;
								break;
							// elseif none of them are null let's compare the counts of the arrays. 
							}elseif(count($result) > 0 || count($result2) > 0) {
								$unique[$x] = true;
								break;
							}

							// If the counts are greater than zero than it means there was a difference in the arrays!
						}

						$i++;
						// Check to make sure that the index of $item is set in post
						// if it is not than this is obviously unique
						if(!isset($_POST[$item])){
							$unique[$x] = true;
							break;
						// Ok the value is set check to see that the type and values are the same
						}elseif ($_POST[$item] === $val) {
							continue;
						// If they are not the same than this is obviously a unique entry!
						}else {
							$unique[$x] = true;
							break;
						}
					}
				}
				$x++;
			}

			// now loop through each item and check to see if it was unique or not
			$myAdd = true;
			foreach ($unique as $index => $uni) {
				if (!$uni) {
					// If any of the uniques are false than we must add one to the quantity
					$_SESSION['shopping_cart'][$_POST['id']][$index]['quantity']++;
					$myAdd = false;
					break;
				}
			}				

			// If it is unique than we want to add a new item to the array at shopping_cart::item::index + 1 ($x) should show the index.
			if($myAdd){
				$_SESSION['shopping_cart'][$_POST['id']][(count($_SESSION['shopping_cart'][$_POST['id']]))] = $_POST;
			}
		}
	}else{
		// Else we are just adding the item to the array
		$add = true;
	}
}else{
	$add = true;
}

// If we are just adding the item lets add the new item in shopping_cart::itemid::index 0 
if($add){
	$_SESSION['shopping_cart'][$_POST['id']][0] = $_POST; // set the item id to the post
}

// lets unset the post data for some reason?
foreach($_POST as $key => $val){ unset($_POST[$key]); }
}
?>

 

My output from this file:

Array
(
    [shopping_cart] => Array
        (
            [12] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                )

                        )

                )

        )

)
Array
(
    [shopping_cart] => Array
        (
            [12] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                )

                        )

                    [1] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 1
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                    [2] => pickles
                                )

                        )

                )

        )

)
Array
(
    [shopping_cart] => Array
        (
            [12] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                )

                        )

                    [1] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                    [2] => pickles
                                )

                        )

                )

        )

)
Array
(
    [shopping_cart] => Array
        (
            [12] => Array
                (
                    [0] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                )

                        )

                    [1] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 2
                            [ingredients] => Array
                                (
                                    [0] => mayonnaise
                                    [1] => tomatoes
                                    [2] => pickles
                                )

                        )

                    [2] => Array
                        (
                            [id] => 12
                            [name] => Sandwhich
                            [price] => 6.5
                            [quantity] => 1
                            [ingredients] => Array
                                (
                                )

                        )

                )

        )

)

Link to comment
Share on other sites

this worked perfectly for me...

<?php
        if(isset($_POST)){
                echo "\$_POST isset<br />\n";
                if(!empty($_SESSION['shopping_cart'])){
                        echo "shopping cart is not empty<br />\n";
                        foreach($_SESSION['shopping_cart'] as $key => $cart_item){
                                if($cart_item['id'] === $_POST['id']){
                                        echo "item exists<br />\n";
                                        if($cart_item['ingredients'] === $_POST['ingredients']){
                                                echo "item is identical. key = {$key}<br /><br />\n";
                                                $identical_index = $key;
                                        }else{ echo "item is not identical<br /><br />\n"; }
                                }
                        }
                        if(isset($identical_index)){
                                echo "there was an identical item in the shopping cart. adding quantity<br />";
                                echo "session item quantity = {$_SESSION['shopping_cart'][$identical_index]['quantity']}<br />\n";
                                echo "post item quantity = {$_POST['quantity']}<br />\n";
                                $_SESSION['shopping_cart'][$identical_index]['quantity'] += $_POST['quantity'];
                                unset($identical_index);
                        }else{
                                echo "there was not an identical item found in the cart. add a new item to the cart.<br />\n";
                                $_SESSION['shopping_cart'][] = $_POST;
                        }
                }else{ $_SESSION['shopping_cart'][] = $_POST; echo "the cart was empty. adding first item<br />\n"; }
                foreach($_POST as $key => $val){ unset($key); }
        }
?>

 

 

if you take out the comments, it totals 17 lines of code. booyakasha! =)

 

you're still the man frost.

Link to comment
Share on other sites

Well shit, I did not know you could compare arrays using the ===, that is new to me. That makes it quite a bit easier. Glad you got it working.

 

man i really appreciate all your help with this. i'm glad we both learned something new =)

 

 

EDIT:

it does NOT work perfectly... but it's SOOOO close. it has to do with the item quantities. if it finds an identical item in the cart, it adds the quantity to every item in the cart, not just the identical item... but other than that, it's perfect. i'm going to look into it further, and post the working code... sorry for the false alarm guys.

Link to comment
Share on other sites

i figured out what's happening. it's not my cart handling code. but for some reason, when i submit my add to cart form and then takes me to cart.php, the POST array prints out, but it doesn't add it to the shopping cart unless i press refresh. and STILL for some reason the UNSET POST won't work either. it would work if i could figure out these two things:

 

1) why i have to refresh to insert the $_POST array into the shopping cart session

2) why the unset post won't work.

 

as i explained before, it's important to unset post, so if the user refreshes their browser, it won't add the same item to the cart again and again.

 

any suggestions as to why these two things aren't functioning properly?

Link to comment
Share on other sites

i talked it over with frost and i found out what the deal was with the why i had to refresh to insert an item into the shopping cart...

 

it was because i was printing my session values before it ran through the cart handler code... i know i know... i'll let that elude me again. here's the new perfectly functioning code:

 

itemTemplate.php

<?php
        session_start();
        session_register();

       /*
        * parameter 1: name of item
        * parameter 2: id of the item
        * parameter 3: price of the item
        * parameter 4: quantity of items
        * parameter 5: ingredients that come with this item
        * parameter 5: all the ingredients that can come with this item
        *
        * prints the name and hidden input field values for this item.
        * populates the checkbox form and compares the ingredient 
        * being populated with the standard ingredients of the item. if
        * there is a match, precheck the ingredient. print price.
        * close form.
        */
        function populateForm($name, $id, $price, $quantity, $standard_ingredients, $all_ingredients){
                echo "
                        <b>{$name}</b>
                        <form action=\"cart.php\" method=\"post\">
                        <input type=\"hidden\" name=\"id\" value=\"{$id}\">
                        <input type=\"hidden\" name=\"name\" value=\"{$name}\">
                        <input type=\"hidden\" name=\"price\" value=\"{$price}\">
                        <input type=\"hidden\" name=\"quantity\" value=\"{$quantity}\">
                \n";

                foreach($all_ingredients as $a_id => $a_ingredient){
                        echo "\t\t\t<input type=\"checkbox\" name=\"ingredients[]\" value=\"{$a_ingredient}\"";
                                foreach($standard_ingredients as $s_id => $s_ingredient){
                                        (($s_ingredient == $a_ingredient) ? (" CHECKED") : (""));
                                }
                        echo ">{$a_ingredient}\n";
                }

                echo "
                        <br /><b>$". number_format($price, 2) ."</b>
                        <br /><input type=\"submit\" value=\"Add to Cart\">
                        </form>
                \n";
        }

        /* set standard ingredients array*/
        $all_sandwich_ingredients = array(3 => 'mustard', 6 => 'mayonnaise', 9 => 'pickles',
                                          1 => 'lettuce', 13 => 'tomatoes', 15 => 'cheese');
        /* set all possible ingredients array*/
        $standard_sandwich_ingredients = array(1 => 'lettuce', 13 => 'tomatoes', 15 => 'cheese');

        /*execute form*/
        populateForm('Sandwich', 12, 6.50, 1, $standard_sandwich_ingredients, $all_sandwich_ingredients);
?>

 

cart.php

<?php
        session_start();
        session_register();

        if(isset($_POST) && !empty($_POST)){
                #$processes[] = "\$_POST isset";
                if(!empty($_SESSION['shopping_cart'])){
                        #$processes[] = "shopping cart is not empty";
                        foreach($_SESSION['shopping_cart'] as $key => $cart_item){
                                if($cart_item['id'] === $_POST['id']){
                                        #$processes[] = "item exists";
                                        if($cart_item['ingredients'] === $_POST['ingredients']){
                                                #$processes[] = "item is identical. key = {$key}";
                                                $identical_index = $key;
                                        }#else{ $processes[] = "item is not identical"; }
                                }
                        }
                        if(isset($identical_index)){
                                #$processes[] = "there was an identical item in the shopping cart. adding quantity";
                                #$processes[] = "session item quantity = {$_SESSION['shopping_cart'][$identical_index]['quantity']}";
                                #$processes[] = "post item quantity = {$_POST['quantity']}";
                                $_SESSION['shopping_cart'][$identical_index]['quantity'] += $_POST['quantity'];
                                unset($identical_index);
                        }else{
                                #$processes[] = "there was not an identical item found in the cart. add a new item to the cart.";
                                $_SESSION['shopping_cart'][] = $_POST;
                        }
                }else{
                        #$processes[] = "the cart was empty. adding first item";
                        $_SESSION['shopping_cart'][] = $_POST;
                }
                $processes[] =  "\$_POST array has been unset";
                foreach($_POST as $key => $val){ unset($key); }
        }

        /*print $_SESSION data*/
        #echo "<b>SESSION ARRAY:</b>\n<pre>\n"; print_r($_SESSION); echo "</pre>\n";

        /*print $_POST data*/
        #echo "<b>POST ARRAY:</b>\n<pre>\n"; print_r($_POST); echo "</pre>\n";

        /*print process*/
        #echo "<b>PROCESS:</b>\n";
        #echo "<ol>\n";
        #foreach($processes as $process){ echo "<li>{$process}</li>\n"; }
        #echo "</ol>\n";

?>

 

problems i'm having with these scripts:

itemTemplate.php : the checkboxes are not pre-checking.

cart.php : $_POST array will not unset.

Link to comment
Share on other sites

  • 4 weeks later...
  • Solution

the reason why $_POST won't unset is because the data is stored in the browser. php can't remove the data on it's own.

 

the checkboxes weren't checking because i didn't echo out my if statement within the foreach loop on the item form page.

 

here's the fixed code:

itemTemplate.php

<?php
        session_start();
        session_register();

       /*
        * parameter 1: name of the item
        * parameter 2: id of the item
        * parameter 3: price of the item
        * parameter 4: quantity of the item
        * parameter 5: ingredients that come with this item
        * parameter 5: optional ingredients for this item
        *
        * prints the name and hidden input field values for this item.
        * populates the checkbox form and compares the ingredient 
        * being populated with the standard ingredients of the item. if
        * there is a match, precheck the ingredient. print price.
        * close form.
        */
        function populateForm($name, $id, $price, $quantity, $standard_ingredients, $all_ingredients){
                echo "
                        <b>{$name}</b>
                        <form action=\"cart.php\" method=\"post\">
                        <input type=\"hidden\" name=\"id\" value=\"{$id}\">
                        <input type=\"hidden\" name=\"name\" value=\"{$name}\">
                        <input type=\"hidden\" name=\"price\" value=\"{$price}\">
                        <input type=\"hidden\" name=\"quantity\" value=\"{$quantity}\">
                \n";

                foreach($all_ingredients as $a_id => $a_ingredient){
                        echo "\t\t\t<input type=\"checkbox\" name=\"ingredients[]\" value=\"{$a_ingredient}\"";
                                foreach($standard_ingredients as $s_id => $s_ingredient){
                                        echo (($s_ingredient == $a_ingredient) ? (" CHECKED") : (""));
                                }
                        echo ">{$a_ingredient}\n";
                }

                echo "
                        <br /><b>$". number_format($price, 2) ."</b>
                        <br /><input type=\"submit\" value=\"Add to Cart\">
                        </form>
                \n";
        }

        /* set standard ingredients array*/
        $all_sandwich_ingredients = array(3 => 'mustard', 6 => 'mayonnaise', 9 => 'pickles',
                                          1 => 'lettuce', 13 => 'tomatoes', 15 => 'cheese');
        /* set all possible ingredients array*/
        $standard_sandwich_ingredients = array(1 => 'lettuce', 13 => 'tomatoes', 15 => 'cheese');

        /*execute form*/
        populateForm('Sandwich', 12, 6.50, 1, $standard_sandwich_ingredients, $all_sandwich_ingredients);
?>

 

cart.php

<?php
        session_start();
        session_register();

        if(isset($_POST) && !empty($_POST)){
                #$processes[] = "\$_POST isset";
                if(!empty($_SESSION['shopping_cart'])){
                        #$processes[] = "shopping cart is not empty";
                        foreach($_SESSION['shopping_cart'] as $key => $cart_item){
                                if($cart_item['id'] === $_POST['id']){
                                        #$processes[] = "item exists";
                                        if($cart_item['ingredients'] === $_POST['ingredients']){
                                                #$processes[] = "item is identical. key = {$key}";
                                                $identical_index = $key;
                                        }#else{ $processes[] = "item is not identical"; }
                                }
                        }
                        if(isset($identical_index)){
                                #$processes[] = "there was an identical item in the shopping cart. adding quantity";
                                #$processes[] = "session item quantity = {$_SESSION['shopping_cart'][$identical_index]['quantity']}";
                                #$processes[] = "post item quantity = {$_POST['quantity']}";
                                $_SESSION['shopping_cart'][$identical_index]['quantity'] += $_POST['quantity'];
                                unset($identical_index);
                        }else{
                                #$processes[] = "there was not an identical item found in the cart. add a new item to the cart.";
                                $_SESSION['shopping_cart'][] = $_POST;
                        }
                }else{
                        #$processes[] = "the cart was empty. adding first item";
                        $_SESSION['shopping_cart'][] = $_POST;
                }
        }

        /*print $_SESSION data*/
        #echo "<b>SESSION ARRAY:</b>\n<pre>\n"; print_r($_SESSION); echo "</pre>\n";

        /*print $_POST data*/
        #echo "<b>POST ARRAY:</b>\n<pre>\n"; print_r($_POST); echo "</pre>\n";

        /*print process*/
        #echo "<b>PROCESS:</b>\n";
        #echo "<ol>\n";
        #foreach($processes as $process){ echo "<li>{$process}</li>\n"; }
        #echo "</ol>\n";
?>

 

remove the hash symbols to follow the procedure for debugging.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.