PHP 2D array fails to increment qty - php

I have a problem updating a multidimensional array in PHP. I'm trying to implement am e-commerce website for a project and I am having problems with the shopping cart implementation.
Basically, I use a session to track the items the user adds to the shopping cart. Here's my logic in plain Pseudo code that is executed once the user clicks the add button after specifying a quantity to add for a product:
RETRIEVE 'cartItems' 2D array from SESSION array
IF 'cartItems' array does not exist in the session create new empty array and add the cartItem sub array to it with the qty and productID
ELSE Loop through the array retrieved from the SESSION array, find the product ID that matches the given product ID (index 0) and update the qty for that subarray (index 1).
Here is my PHP script addToCart.php which in turn calls another function in another script file that is included in it:
<?php
require_once("cart_utility.php");
session_start();
// Script for adding a given product to the client's cart through the use of Ajax and sessions
// retrieve values from ajax request
$productID = $_GET["productID"];
$qty = $_GET["qty"];
$cartItems = null;
// use sessions to add the items to the user's cart
// retrieve the multi-dimensional cart array if it exists, otherwise create one and add it
if(isset($_SESSION["cartItems"])){
$cartItems = $_SESSION["cartItems"];
}
else{
$cartItems = array();
}
addQtyForProduct($productID, $qty, $cartItems);
$_SESSION["cartItems"] = $cartItems;
print "Session cartItems after function return: ";
var_dump($_SESSION["cartItems"]);
// return info string with new qty of cart items
print ("success-" . getTotalCartItems($cartItems));
?>
And here's the other script file that does the handling of inserting and updating the array:
<?php
// Utility functions for retrieving items from the 2D cart items array
/* The array structure is given as (example values):
* | productID | qty |
* 0 | 1 | 3 |
* 1 | 2 | 1 |
* 2 | 5 | 8 |
* 3 | 8 | 3 |
*/
// increments the qty for the given product. If it does not exist then it is added into the main session array
// $cartItems: the main 2D array with the structure given above, pass by reference to change the array
function addQtyForProduct($productID, $qty, &$cartItems)
{
foreach($cartItems as $cartItem)
{
var_dump($cartItem);
if($cartItem[0] == $productID){
//print "Quantity given to increment: $qty";
//var_dump($cartItem);
print "Qty in current session array: $cartItem[1]";
$cartItem[1] += $qty;
print "New qty in cartItem array: $cartItem[1]";
return;
}
}
// not found, therefore add it to the main items array
array_push($cartItems, array($productID, $qty));
}
// returns the total number of items in the cart
function getTotalCartItems($cartItems)
{
$total = 0;
foreach($cartItems as $cartItem)
$total += $cartItem[1];
return $total;
}
?>
I have placed some var_dump statements and can confirm that upon returning from the function 'addQtyForProduct', the array is not updated. But why? I pass the array by reference to directly alter it's contents.
It successfully adds on the first time when there is no existing array but fails to increment if the array exists.
Also, the values are successfully incremented in the 'addQtyForProduct' function but the array somehow is not updated when it returns from the function.
I would gladly appreciate some help on this. I've been trying to understand this for days now and It's driving me nuts.

As read on this page you should use references. Add a & in front of your $cartItem and your script should work. Right now PHP stores a 'copy' of every value in your array in $cartItem, rather than it's reference. So currently you are editing a copy of the original, rather than the original array.

Related

Collect product variable and find the largest one in php

I am writing some code to supply the Google certified shop data which I have nearly finished. I only need to supply the ship and delivery dates. I have written code to supply this information at the product level. However when there is more than one product in an order I need to select the largest ship date.
For example;
Order has two products.
Producta with $ship_date = 2 and porductb with $ship_date = 5
I need to collect all the $ship_dates (2 and 5) and return the highest one (5).
My question is simply how do I write the php to collect all the $ship_dates correctly - should I create an array and if so how?
Put all the required variables into an array, then use max.
$ship_date1 = 2;
$ship_date2 = 5;
$shipDates = [$ship_date1, $ship_date2];
// other dates as needed
// OR, a much cleaner solution, append to the array
$shipDates = [];
$shipDates[] = 2;
$shipDates[] = 5;
//No matter how you fill up the array, this is how you get its maximum value
$maxShipDate = max($shipDates);
max actually accepts individual variables instead (eg. max($ship_date1, $ship_date2);) but the array solution is easier to maintain.
OK before my foreach product loop I added this;
$deliverydatearray = array();
which creates a new (empty) array which I called $deliverydatearray
Within my foreach product loop I added this;
$deliverydatearray[] = $delivery_datep;
which adds my product specific delivery date ($delivery_datep) to my array.
After the foreach product loop has closed I can access the variables in my array. For example just printing the contents of the array is done like this;
print_r($deliverydatearray);
which looks like this;
Array
(
[0] => 2017-01-28
[1] => 2017-01-23
)

multi dimension session array

I am using a form that is pulling data from two MySQL databases into a single dynamic page. When a user clicks add to cart I want to store that data in a multi dimensional session array to call up later when they click view cart. I am wondering how to auto increment the subset identifier(array key?) of the item when a new item is added from the add to cart form. This is what I have so far:
$newitem = array ($row_getimages['icon'],$row_getimages['title'],$row_getshoppingcart['medium'],$row_getshoppingcart['size'],$row_getshoppingcart['price'],$row_getshoppingcart['shipping']);
session_start();
if(isset($_SESSION['item'][1]))
$_SESSION['item'][1] = $_SESSION['item'][1]+ 1;
else
$_SESSION['item'][1] = 1;
Also any help for calling out the data later would be appreciated. As a user may have 1 or 20 items stored in the session I am not sure how to make sure all items would be echoed no matter how many they have added.
This is my first time at a multi dimensional array and sessions. Obviously because the image page is dynamic and purchase price is based on several factors, just using a MySQL database of available items as I have in the past is out of the question.
Thank you in advance for your time.
$newitem = array ('id' => $row_getshoppingcart['id'] , 'icon' => $row_getimages['icon'],'title' => $row_getimages['title'],'medium' => $row_getshoppingcart['medium'],'size' => $row_getshoppingcart['size'],'price' => $row_getshoppingcart['price'],'shipping' => $row_getshoppingcart['shipping']);
session_start();
$_SESSION['item'][] = $newitem;
That is all you have to do, if I understand your system correctly.
UPDATE
I updated the $newitem array to include array keys. You can reference the new item info with arrays like this:
$_SESSION['item'][(num)]['id']
Or you can loop through the results like this:
foreach ( $_SESSION['item'] AS $item )
{
echo 'id: ' . $item['id'] . '<br />';
echo 'title: ' . $item['title'];
// and so on
}
If it is not important for the numbers to be sequential, you can use:
$_SESSION['item'][] = array('a','b','c','d','e','f');
Using [] will simply add a new element to the end of the array.
However, I would probably use a product ID for the key.

Implementing cart system using Multidimensional Associative php array

I am not getting the concept of two dimensional arrays in PHP. I am trying to implement a cart system in which an array Session variable store productid and the quantity of it.
For every new entry if it exists its quantity should be increased or if it does'nt then a new id should be added.
Here is my initial code.
function cart_increment_ajax($data, $qtt) {
$_SESSION['count']+=$qtt;
set_cart( $data );
echo $_SESSION['count'];
}
function initialise_cart( ) {
$_SESSION['cart'] =array( );
$_SESSION['totalprice'] = 0;
}
function set_cart( $pid ) {
if(!isset($_SESSION['cart'])) {
initialise_cart( );
}
//else if( int $_SESSION['cart'] pid exists increment count ))
else
// ($_SESSION['cart'] add new pid.
}
I am not getting how to implement the commented lines through Multidimensional associative array ?
A small quick n dirty example of a multi-array in a session keeping a cart
<?php
function add_to_cart($product_id,$count)
{
// no need for global $_SESSION is superglobal
// init session variable cart
if (!isset($_SESSION['cart']))
$_SESSION['cart'] = array();
// check if product exists
if (!isset($_SESSION['cart'][$product_id]))
$_SESSION['cart'][$product_id]=$count;
else
$_SESSION['cart'][$product_id]+=$count;
}
// add some foos and a bar
add_to_cart('foo',2);
add_to_cart('foo',1);
add_to_cart('bar',1);
print_r($_SESSION['cart']);
?>
This will produce
Array
(
[foo] => 3
[bar] => 1
)
HTH
Use the product ID as an index in your array, then simply increment it by using ++.
$_SESSION['cart'][$pid]++;

Replicate javascript Array in php

I have a shopping cart type arrangement. The customer builds the order in tiers. So page one is item 1, page 2 item 2....... The page does not reload during the building of a order. (jqtouch) My way of building the order is add each item to an array. Below is how I have created the array.
var item_contents= new Array();
so typical order with two items would look something like..
item_contents[0] = 627
item_contents[1] = 451
item_contents[2] = 365
item_contents[3] = 548
item_contents[4] = 158
item_contents[5] = 154
item_contents[6] = 155
item_contents[7] = 115
The number is the item_id number in a database. The user has the ability to go back and alter an item in the array for the current order.
When the checkout screen is shown this needs to be submitted and details for the respective item_id returned. I guess the best way would be someway to replicate the array above in php. How Would I POST an array like this and get it to look identical in php?
Thx
jquery post
var a = [627,451,365,548,158,115,155,115];
$.post("ajax.php",{data: a},function(data){
console.log(data);
});
php
<?php
$array = json_decode($_POST['data']);
foreach($array as $key => $value){
add(sanitize($value[$key]));
}
?>

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