Reputation: 53
Im buliding a shopping cart and want to use a 2d array to store the items ID and quantity. When the user goes to the shopping cart I want to be able to grab the Items ID from the array and output the items details from the database
/**************** Adding to the 2d array ***********************/
//Check to see if variable isset and then add item to shopping cart
//$itemID is the ID of the product
//$quantity is the quantity of the product they wish to order
if(isset($_GET['add'])){
$itemID = $_GET['add'];
$quantity = $_POST['quantity'];
$_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
header('xxx');//stops user contsanlty adding on refresh
}
/******************** Looping through the array **********************/
//need to loop through grab the item ID
//then pull what we need from the database
//This is where I want to grab the id from the array and query the database
$cart = $_SESSION['cart'];
foreach ($cart as $value ){
//works like it should
foreach ( $value as $key=> $final_val ){
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
echo '<br/>';
}
The array outputs like so
id:1 quantity:5
id:2 quantity:1
Im having a little trouble figuring out how to seperate the ID and quantity so that I can query the database with the item ID.
Upvotes: 0
Views: 1543
Reputation: 3677
foreach ( $value as $key=> $final_val ){
if($key=='id')
{
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
}
or you can directly use like $value['id']
something like this will help you..please try.
is this you need?
Upvotes: 1