How to unset / remove item from two dimensional associative array - php

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);

Related

Append array key value to a session array

Want to append a key and value to the already created session.
if (!isset($_SESSION['cart'])) {
$bag = array(
"sessionId" => session_id(),
"productId" => $productId,
"size" => $productSize,
"quantity" => $productQuantity
);
$_SESSION['cart'] = $bag;
} else {
$_SESSION['cart']['sessionId'] = session_id();
$_SESSION['cart']['productId'] = $productId;
$_SESSION['cart']['size'] = $productSize;
$_SESSION['cart']['quantity'] = $productQuantity;
}
If session has already been created, then append the new variables to the session with its keys.
$_SESSION['cart'] should be an array of items, not a single item as you've written it. Each item will be a separate associative array, which you push onto the cart array.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
$bag = array(
"sessionId" => session_id(),
"productId" => $productId,
"size" => $productSize,
"quantity" => $productQuantity
);
$_SESSION['cart'][] = $bag;

catalogProductUpdate multiple category IDs

I'm trying to update the website and category IDs for a number of products in Magento and I'm having issues. Here's my code:
$client = new SoapClient('http://magentohost/api/v2_soap/?wsdl');
$session = $client->login('apiUser', 'apiKey');
$productarray = array("12345" => "1,2,3", "67890" => "1,5,6");
foreach ($productarray as $product_id => $cats) {
$update = array(
'websites' => array(1,2,3),
'categories' => array($cats)
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}
When I run this code, it's changing the products to have the new website IDs but it's only updating the category IDs with the first one in $cats.
For example, "12345" will only have category ID 1 and not 2 or 3 as it should have.
When I print out what $cats is for each product, it's showing me the info correctly (as "1,2,3" and "1,5,6" for the examples above).
I'm not sure what I've done but I just can't seem to get it to update all the category IDs. I've got thousands of products to run through that all have different category IDs so I can't be doing this manually!
EDIT - SOLVED
I've changed my code so it's now like this (which works):
$client = new SoapClient('http://magentohost/api/v2_soap/?wsdl');
$session = $client->login('apiUser', 'apiKey');
$productarray = array("12345" => "1,2,3", "67890" => "1,5,6");
foreach ($productarray as $product_id => $cats) {
$cats = explode(",", $cats);
$update = array(
'websites' => array(1,2,3),
'categories' => $cats
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}
The categories property would expect an array of IDs, whereas you're passing a string. Try using explode() to break it up:
foreach ($productarray as $product_id => $cats) {
$update = array(
'websites' => array(1,2,3),
'categories' => explode(',', $cats)
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}

Getting the highest element from an array

I have a query which gives me a tuple of a discount added into database.
Here's the query
$discount_info = $this->autoload_model->get_data_from_table("td_discount,td_userdiscount","*",
"td_discount.discount_id = td_userdiscount.discount_id
AND td_discount.discount_code = '$coupon'")->result_array();
Now i have script which does the specific function.
There will be a condition, if the value of a index will be 1, then the code snippet is like this
if($discount_info[0]['discount_on']=="3")
{
$discount_product = $discount_info[0]['discount_product']; // its an id(autoincrement value)//
if($discount_info[0]['applicable_type']==1)
{
$item_info = $this->autoload_model->get_data_From_table("td_product","*","product_id = '$discount_product'")->result_array();
foreach($this->cart->contents() as $ci)
{
if($ci['name'] = $item_info[0]['product_name']
{
// get the cart_item with the highest price if the product name matches//
}
}
}
}
My cart structure is like this
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'options' => array(
'picture'=>$img,
'item_slug'=>$slug,
'item_color'=>$color,
'item_size'=>$size,
'unit_price'=>$price,
'order_type'=>$order_type,
'product_type'=>$pro_type,
'unit_discount' => 0.00,
'item_discount' => 0.00,
'discount_type' => '',
)
);
Now, its all set up, but I just can't get the login which I shall put over here
// get the cart_item with the highest price if the product name
I imagine you could just define a
$highest = array('price' => 0);
before the loop and then inside the loop go:
// get the cart_item with the highest price if the product name matches//
if ($ci['price'] > $highest['price']) {
$highest = $ci;
}
That way $highest would contain the best match at the end.

deleting and changing values in multidimensional array php

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;

Find sum of all keys in Session array

I am using a form to create several arrays in a Session. Each time the form is submitted a new _SESSION['item'][] is made containing a new array. The code for this:
$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['item'][] = $newitem;
There could be any number of item arrays based on how many times the user submits the form. How can I get the total of the key 'price' from every item in the entire session and echo it on the page?
Thank you in advance for your time. I really appreciate it.
Try this (untested):
$sum = 0;
foreach ($_SESSION['item'] as $item)
$sum += $item['price'];
echo $sum;
Loop through them:
$total = 0;
foreach($_SESSION['item'] as $item) {
$total += $item['price'];
}
echo $total;

Categories