Append array key value to a session array - php

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;

Related

PHP in_array not working after loop in session

I have a foreach loop to check all array of ID and if using in_array to see if any of the arrays of IDsis equaled my $_POST['id'] as shown below:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
For some reason, it keeps adding even when the ID exist inside the list of arrays of IDs.
You are just changing the value of $id inside foreach loop. Try to store value in array. Refer the below code:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}

How to add elements of other arrays in an array

I have two arrays, one of product titles and another of quantities. I need to store them in a new array, which has in its first position "title" and "quantity".
This is what I thought:
//arrayTitle and arrayQuantity already come with stored data, both arrays of the same length
$newArray[];
for($i=0;$i<count($arrayTitle);$i++){
$newArray = array("title" => value of the position $i of the title array,
"quantity" => value of the position $i of the quantity array);
}
Try it with an foreach loop, like:
foreach ($arrayTitle as $i => $title) {
$newArray[] = [
'title' => $title,
'quantity' => $arrayQuantity[$i]
];
}
Just map them to callback that returns them in your array format:
$newArray = array_map(function($t, $q) {
return array("title" => $t, "quantity" => $q);
}, $arrayTitle, $arrayQuantity);

How to unset / remove item from two dimensional associative array

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

PHP array within array

Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array.
foreach($json['area'] as $row) {
$name = $row['name'];
$group = $row['array']['group'];
$majority = $row['array']['majority'];
$candidates = $row['array']['candidates'];
foreach ($candidates as $candidate) {
$vote = $candidate["votes"];
$candi = $candidate["name"];
$votes = array("vote" => $vote, "candidate" => $candi);
}
$array = array("name" => $name, "group" => $group, "majority" => $majority, "votes" => $votes);
$results[] = $array;
}
Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line:
$votes = array("vote" => $vote, "candidate" => $candi);
If you want to capture multiple entries in that array for each row, you need to make it a multi-dimensional array also:
$candidates = $row['array']['candidates'];
$votes = [];
foreach ($candidates as $candidate) {
$votes[] = array(
"vote" => $candidate["votes"],
"candidate" => $candidate["name"]
);
}
$array = array(
"name" => $name,
"group" => $group,
"majority" => $majority,
"votes" => $votes
);

Search for specific value in array with keys

I have an array that is filled with values dynamically and I have to check if a value exists.
I tried the follwing but it's not working:
while (.....) {
$fileData[] = array( "sku" => $sku, "qty" => $qty);
}
$product_sku = $product->getSku();
if (in_array(array("sku",$product_sku), $fileData)){
echo "OK <BR/>";
}
else{
echo "NOT FOUND <BR/>";
}
The whole thing with keys confuses me. Should I change the table structure or just the in_array() statement? Can you help me find a solution?
You can see if a key exists in an array with:
array_key_exists('sku', $fileData);
also, you can just check it directly:
if (isset($fileData['sku'])
It looks like you might be trying to recursively check for a key though? I think we'd need to see what getSku() returns. $fileData[] appends a value to an existing array so if $fileData was an empty array you'd have
fileData[0] = array("sku" => $sku, "qty" => $qty);
not
fileData = array("sku" => $sku, "qty" => $qty);
Try this on for size (with some fake data for demo purposes):
$fileData = array(
array("sku" => "sku1", "qty" => 1),
array("sku" => "sku2", "qty" => 2),
);
$sku = "sku2"; // here's the sku we want to find
$skuExists = false;
// loop through file datas
foreach ($fileData as $data)
{
// data is set to each array in fileData
// check if sku exists in that array
if (in_array($sku, $data))
{
// if it does, exit the loop and flag
$skuExists = true;
break;
}
}
if ($skuExists)
{
// do something
}

Categories