PHP multi-dimensional array issue
Posted by: crimsondryad
Posted on: 2006-04-29 07:06:00
Hi! I'm trying to add items to my shopping cart using PHP. I'm allowing item options that may modify the item, ie item num 123 may have options s, l, xl. If the user has an item in the cart that is "s" and add an "xl", the cart should add a new item rather than update the qty because the actual item is different.
Currently, I'm using multidimensional arrays in the Session to do this. But...it's not working. What I really need to do is an exact comparison on the option array of the item the user is trying to add to what is already in the cart. I looked in the PHP manual, considered using array_diff, but a) I don't know if it will work on the subarrays in the main options array b) the manual doesn't say what array_diff returns if the arrays are exactly alike.
The structure of the array is like this $_SESSION["item"][0]["options"]["Color"][0] = "12 if the subarray of options is an array or $_SESSION["item"][0]["options"]["Size"]= "1" if the options subarray only contains a value.
If there is an easier way to do this, please let me know. This is my first shopping cart app and also my first attempt at using multidimensional arrays, so maybe I'm making this a lot harder than it has to be.
$options is the array of the item the user is trying to add.
Here's the code:
foreach ($options as $opt_key => $opt_value) {
if(!array_key_exists($opt_key, $_SESSION["item"][$key]["options"])) {
$update_qty = "n";
}
else {
$sess_sub_value = $_SESSION["item"][$key]["options"][$opt_key];
//debug start
if(is_array($sess_sub_value)) { echo "<h1>Session Sub</h1>"; foreach($sess_sub_value as $sub_key => $sub_value) { echo $sub_key ." = ".$sub_value."
"; }}
else {
echo "<hr>
session sub value=".$sess_sub_value."
"; }
//debug end
// I think the problem is here. If it finds one value the same, it changes to update and it shouldn't. I think I should be using a diff here or something.
if(is_array($opt_value)) {
foreach($opt_value as $opt_sub_key => $opt_sub_value) {
if((in_array($opt_sub_value, $sess_sub_value)) || ($update_qty !=="n")){
$success["result"] = "n";
$success["loop2"] = "2causing issues";
$update_qty = $key;
// change to yes
echo "
Loop 2 hits here
";
}
else {
$update_qty="n";
continue 3;
}
}
}
else {
// put stuff here
if(($opt_value !== $sess_sub_value)||($update_qty =="n")){
$update_qty ="n";
// change to yes
$success["result"] = "n";
$success["loop4"] = "4causing issues";
}
else {
$update_qty=$key;
continue 2;
}
}
}
}
================================
CrimsonDryad Web Design Services
Web Design, Custom Software Development
http://www.crimsondryad.com