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 each 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. Any ideas how can I get the value of the array key that is being put in place of the [] in the session variable? I am trying to create a remove from cart option and cannot figure out how to reference that particular array in the session to unset it.
I am currently displaying the items as such:
<?php foreach ( $_SESSION['item'] AS $item )
echo $item['title'];
echo $item['icon'];
and so on...
Thank you in advance for your time. I really appreciate it.
foreach($_SESSION['item'] as $key => $value) will enable you to seperate the key and value, and ofcourse, to access the value current key has.
To extend this with an example, consider following code:
<?php
$exArray = array("foo"=>"bar", "foo2"=>"bar2);
foreach($exArray as $arrKey => $arrValue):
echo "The key ".$arrKey." has the value of ".$arrValue."<br />\n";
endforeach;
?>
will output:
The key foo has the value of bar.
The key foo2 has the value of bar2.
However, in the same way, if the $arrValue variable is known to hold an array, it will keep it's content. To loop through that second array, you will need to loop it through another foreach statement.
Just specify an index name in your foreach
foreach ($_SESSION['item'] as $idx => $item) {
var_dump($item);
var_dump($_SESSION['item'][$idx]);
}
The var_dumps will be the same.
$var = array_keys($arr);
$count = count($var);
$lastKey = $var[$count - 1];
That work for you?
Related
I have the following array:
$array = array(
array("2018","2019"),
"Jan",
array("France","Germany")
);
I need a matrix that crosses all the elements of the array; e.g:
array(
array("2018","Jan","France"),
array("2018","Jan","Germany"),
array("2019","Jan","France"),
array("2019","Jan","Germany")
);
meaning, 2 x 2 x 1 arrays
but this can be that I have more elements that are or are not arrays then:
$array = array(
array("2018","2019"),
"Jan",
array("France","Germany"),
array("prod1","prod2","prod3"),
'Act'
);
In this case I would get 2 x 2 x 1 x 4 x 1 arrays in the end.
Any idea on how to achieve this?
Is that what you are looking for ?
$dst = array(array());
foreach ($array as $idx => $val) {
foreach ($dst as $tmp_idx => $tmp_array) {
if (is_array($val)) {
foreach ($val as $sub_idx => $sub_val) {
$dst[] = array_merge($dst[$tmp_idx], array(count($dst[$tmp_idx]) => $sub_val));
}
} else {
$dst[] = array_merge($dst[$tmp_idx], array(count($dst[$tmp_idx]) => $val));
}
unset($dst[$tmp_idx]);
}
}
I declare the array with an empty array in it.
A first foreach iterates through the main array to access all the categories, whatever their number.
A second foreach iterates through the result array.
A third foreach - or not, depending if the category contains several or a single entry - iterates through each entry of the current category and merges an array containing only that current category in the result currently iterated on (from $dst). The merge is pushed into the result array. The result stored in $dst are assumed to be temporary and will be copied and completed with each new value, making them progressively contain one entry from each category.
At the end of each iteration on $dst, the current temporary result is removed from the array since it has no purpose : if the foreach iterated on it, that means that it was incomplete.
At the end, the only entries in $dst that remain are these who weren't iterated on, meaning that every entry from each category were considered when they were created, meaning that they are complete.
I'm available for any clarification may the need arise.
I have an issue on how can I update my Previous array ?
What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:
//get the array of items (you will want to update) from the session variable
$old_items = \Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
\Session::put('items',array_merge($old_items,$new_item));
You can use Session::forget('key'); to remove the previous array in session.
And use Session::push to add new items to Session.
I'm creating a multi-dimensional array to match the hierarchy of a company. I ask the database for the downline (saved in a seperate table) and start looping it. Currently I'm only doing this for the highest level and the people below him. I know he has 6 people below him, thus the end result only shows one. When I var_dump $complete every time in the loop, I see different values in the children-array. (AKA he overwrites instead of adds up).
I've tried both array_push and this method, I hope I've been clear enough, because I probably don't (sorry.)
The code:
foreach ($downpositions as $downposition) {
// start position
if ($downposition['PositionsDownposition']['positionsdownpositions_rel_position'] == 1) {
// check downline only on first level
if ($downposition['PositionsDownposition']['positionsdownpositions_level'] == 1) {
foreach ($downpositions as $mother) {
if ($mother['PositionsDownposition']['positionsdownpositions_rel_downposition'] == 1) {
// format it
$node = array(
'id' => $downposition['PositionsDownposition']['positionsdownpositions_id'],
'name' => $downposition['PositionsDownposition']['positionsdownpositions_rel_position'],
'children' => array()
);
$complete = array(
'id' => $mother['PositionsDownposition']['positionsdownpositions_id'],
'name' => $mother['PositionsDownposition']['positionsdownpositions_rel_position'],
'children' => array()
);
// add up to array
$complete['children'][] = $node;
}
}
}
}
}
Found the problem, im intialising $complete['children'] in the loop, thus resetting the array to empty all the time.
Solution:
Re-do the code, initialise of $complete outside the loop.
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.
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!