I've got a session called Cart_array which holds a multidimensional array in the following way:
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
this is how items are added to the cart session. pid is obtained from another form
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
if (!isset($_SESSION['Cart_array']) || count($_SESSION['Cart_array']) < 1) { //check if cart session is not set or empty
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
} else {
array_push($_SESSION['Cart_array'], array(
"ID" => $pid,
"QTY" => 1
));
} //end else
} //end if
the user has a form with the following things in a function:
<?php foreach ($_SESSION['Cart_array'] as $eachItem) {
$itemID = $eachItem['ID'];
$itemQty = $eachItem['QTY']; >?
<input class="qty" name="quantity" type="number" value="<?php echo $itemQty;?>" />
<input type="submit" name="qtyChange<?php echo $itemID;?>" value="Change Qty" />
<input name="qtyOfItem" type="hidden" value="<?php echo $itemID?>"/>
}
This form will go through the Cart_array and display the quantity in the cart for every item.
I want the user to be able to change the quantity in the cart for the specific item that they chose when they click the Change Qty button
I'm not sure how to go around doing this?
You could edit the array like this
Your Array
$list = array([0]=>
array(
[ID]=>'XYZ'
[QTY]=>'1'
)
);
my_function()
{
$list=$_SESSION['Cart_array'];
global $list;
$list[0]['QTY'] = '2'; //or this 2 value can be taken from user using jquery
}
my_function();
For the script that this submits to, you want to loop through each item in the cart_array session and find it by that ID then change the quantity for that item.
foreach($_SESSION['cart_array'] as $index => $item){
if($item['ID'] == $_POST['ID']){
$_SESSION['cart_array'][$index]['quantity'] = $_POST['quantity'];
}
}
Just pass your quantity value from the user like this
<?php
$_SESSION['Cart_array'] = array(
1 => array(
"ID" => $pid,
"QTY" => 1
)
);
$_SESSION['Cart_array'][1]['QTY']=30;//Relaces the quantity from 1 to 30
Related
I have a script which puts products into a shopping cart;
if (isset($_POST["top"])) {
$name = $_POST["name"];
$_SESSION[$$name] += 1;
$$name = $_SESSION[$$name];
$name = $name.$$name;
$piid = $_SESSION["piid"];
$prod = $_POST["prod"];
$_SESSION["cart"][$name] = array("id" => $prod, "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
foreach ($piid as $value) {
$ab = $value[id];
$qty = $_POST["htop".$ab];
if ($qty > 0) {
$piid[] = array("id" => $row["ID"], "des" => $row["des"], "hid" => $row["hide"]);
$_SESSION["cart"][$name]["top".$value[id]] = array("id" => $value[id], "dec" => $value[des], "qty" => $qty);
}
}
} else {
$name = $_POST["name"];
$name = $name.$$name;
if (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] === $_POST['des'])) {
$_SESSION['cart'][$name]['quantity'] += 1;
} elseif (isset($_SESSION['cart'][$name]) && ($_SESSION['cart'][$name]['des'] <> $_POST['des'])) {
$_SESSION[$$name] += 1;
$name = $_SESSION[$$name];
$_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
} else {
$_SESSION["cart"][$name] = array("id" => $_POST["prod"], "name" => $_POST["name"], "quantity" => 1, "des" => $_POST["des"]);
}
}
To avoid confusion in the array when items have different description it will set a multi-dimensional array by using the product's name and an incremental id (where required)
Now my question is how do I get a remove button to work something like this?
I need to pass that sub-array's name/key as a variable so we can then pass that back to the POST method.
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post"
enctype="application/x-www-form-urlencoded">
<button type="submit">Remove
<input type="hidden" name="rprid" value="' .$name. '" />
<button</form></div>
Thanks!
I've managed to figure out the code I need which should be a follows;
foreach($cart as $key => $value)
{
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="application/x-www-form-urlencoded"><button type="submit">Remove<input type="hidden" name="rprid" value="' .$key. '" /></form></div>';
}
Thanks for the thoughts all!
Edit: The solution is to use $key => $value that way you can simply use $key to return the key which you are looking at.
I am trying to build a dynamic Menu from data I generate from jstree.
Jstree values will stored in database as follows:
Id | Name | Parent | Icon | Link
So I've made a method to read each row from database(propel) and store it in array, so Smarty can build a menu dynamically.
That's my function:
$menu_content = array();
foreach($result as $key => $r) {
if($r['Id'] != 1) {
$Id = $r['Id'];
$menu_content[$r['Id']] = array(
"name" => $r['Name'],
"link" => $r['Link'],
"icon" => $r['Icon']
);
unset($result[$key]);
foreach($result as $key_children => $c) {
if($c['Parent'] == $r['Id']) {
$menu_content[$r['Id']]['children'][] = array(
"name" => $c['Name'],
"link" => $c['Link'],
"icon" => $c['Icon']
);
unset($result[$key_children]);
$Idc = $c['Id'];
foreach($result as $key_grandchild => $cc) {
if($cc['Parent'] == $c['Id']) {
$menu_content[$r['Id']]['children']['grandchild'][] = array(
"name" => $cc['Name'],
"link" => $cc['Link'],
"icon" => $cc['Icon']
);
unset($result[$key_grandchild]);
}
}
}
}
}
So it should store values like this:
$menu_content[parent][children][grandchildren].
This part of code is working fine, but it's not unsetting the children and grandchildren values, so I get them twiche. First time in correct order and after that as parent children.
Thanks in advance.
I'm trying to post and receive a two dimensional array, but I can't get it to work.
Could you guys help me out?
Thanks in advance!
Here is my code:
$items[] = array(
'pid' => $pid
, 'qty' => $product_qty
);
<input type="hidden" name="items[]" id="pid" />
foreach ($_POST['items'] as $row) {
$pid = $row['pid'];
$product_qty = $row['qty'];
}
Change your code in a way like this:
$items = array('pid' => $pid, 'qty' => $product_qty);
foreach( $items as $key => $val )
{
echo '<input type="hidden" name="items['.$key.']" value="'.$val.'" id="'.$key.'" />';
}
In your original code, $items[] add a new item to array $items.
Also, HTML doesn't interpret php variables, so your <input name="items[]" will produce $_POST[items][0] with an empty value.
It's as simple as this:
$myarr = array( 'pid' => array($pid), 'qty' => array($product_qty));
On sound advice from this Forum, I am re-writing code involving multi-dimensional array SESSIONS cart so that the product ID is the array name (I think I am explaining this correctly). I can add to the array, but I cannot remove anything. I am using an array to add new item data to the SESSIONS array. The code below represents a test adding items to the array and finally trying and failing to delete one. Any assistance in finding my errors is appreciated.
echo '************** STEP ONE **********************';
// Initialize array
$_SESSION['cart'] = array();
// Array of newitem
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with one item
var_dump($_SESSION['cart']);
echo '************** STEP TWO **********************';
// Array of newitem
$id = 33;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7170-11',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with two items
var_dump($_SESSION['cart']);
echo '************** STEP THREE **********************';
// Array of newitem
$id = 34;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7171-15',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with three items
var_dump($_SESSION['cart']);
echo '************** STEP FOUR **********************';
// Unset by ID
$id = 34;
unset($_SESSION['cart'][$id]);
// Display cart array with two items
var_dump($_SESSION['cart']);
When you use $_SESSION['cart'][] it adds a new array item dynamically with the next index. You are then adding another two arrays under that one. Try creating the index with the specific $id:
$id = 181;
$newitem = array(
'quantity' => 1,
'part_number' => '600N5630-501',
);
// Add newitem to cart
$_SESSION['cart'][$id] = $newitem;
Alternately you could add/replace them like this:
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'] = array_replace($_SESSION['cart'], $newitem);
I've got the following code to remove 1 from the qty when a remove button is pressed and if the qty=1 the item will be removed from the array at the specific index.
for example if the first item in the array has an ID of '1B' and qty of '5' and name 'item1' second item in the array has the ID of '2B' and qty of '3' and name 'item2' and the remove button for this item is pressed, the qty will change to 2(as required) but the id will change to 1B and the name to 'item1'. The same thing happens if there are more than 2 products in the $_SESSION["Cart"] array.
I'm not sure where i'm going wrong, but this is my code:
code for $_SESSION["Cart"]
$_SESSION["Cart"] = array(
array(
'name' => "namehere",
'id' => "idHere",
'qty' => 1,
'price' => "pricehere"
)
//more arrays here
);
Code for Removing item
$prodID = $_GET["removeProd"];
foreach ($_SESSION["Cart"] as $cartItem) {
//only continue if qty is more than one
//remove item if 0 qty
if ($cartItem["id"] == $prodID) {
if ($cartItem["qty"] > 1) {
$qty = $cartItem["qty"] - 1; //decrease qty by one
$cart[] = array(
'name' => $cartItem["name"],
'id' => $cartItem["id"],
'qty' => $qty,
'price' => $cartItem["price"]
);
} //end if
} else {
$cart[] = array(
'name' => $cartItem["name"],
'id' => $cartItem["id"],
'qty' => $cartItem["qty"],
'price' => $cartItem["price"]
);
} //end else
$_SESSION["Cart"] = $cart;
} //end foreach
The problem is that you're assigning $_SESSION['Cart'] = $cart on each iteration, so it will only ever contain the last item in the $_SESSION['Cart'] array. If you move it below the end of the foreach your code should work.
You could simplify this a bit by passing $cartItem by reference. That way you only modify array elements which match $prodID:
foreach ($_SESSION['Cart'] as $key => &$cartItem) {
if ($cartItem['id'] == $prodID) {
if ($cartItem['qty'] > 1) {
$cartItem['qty'] -= 1;
} else {
unset($_SESSION['Cart'][$key]);
}
}
}
unset($cartItem); // break the binding
Your code has some algorhithmic/logic flaws. This code should do what you need it to do. Please try to find out what it actually does, and where are the flaws in your approach.
foreach ($_SESSION["Cart"] as $key=>$cartItem) {
//only continue if qty is more than one
//remove item if 0 qty
if ($cartItem["id"] == $prodID) {
if ($cartItem["qty"] > 1) {
$qty = $cartItem["qty"]--;// does the same thing as x = x - 1; //decrease qty by one
$cart[$key]['qty'] = $qty;
} //end if
else {
unset($cart[$key]);
}
break;// ends foreach loop ( assuming there can be only one item of the same type in the cart )
}
} //end foreach
$_SESSION["Cart"] = $cart;