Reputation: 4813
I've having a problem with an Array that I'm storing in the session variables. When I try to make a change to a particular item in the array, the entire array gets overwritten with the new values.
My code is as follows:
<? session_start();
include '../../config/config.php';
include '../functions.php';
if ($user){
$type = str_replace("-", "_", ucwords(sanitize($_POST['type'], 'u')));
$name = str_replace("-", "_", ucwords(sanitize($_POST['name'], 'u')));
$price = sanitize($_POST['price'], 's');
$num = sanitize($_POST['num'], 's');
preg_match_all('/[-+]?\b[0-9]+(\.[0-9]+)?\b/', $price, $result);
if ($num != ""){
$num = explode("-", $num);
echo '<pre>';
print_r($num);
echo '</pre>';
echo '<br/>';
echo '<pre>';
print_r($_SESSION['prodcontrolprices']);
echo '</pre>';
switch(count($num)){
case 2:
$_SESSION['prodcontrolprices'][$num[0]][$name] = array("price"=>$price);
echo "1here";
break;
case 3:
$_SESSION['prodcontrolprices'][$num[0]][$num[1]]['subs'][$type][$name] = array("price"=>$price);
echo "2here";
break;
case 4:
$_SESSION['prodcontrolprices'][$num[0]][$num[1]][$num[2]]['subs'][$type][$name] = array("price"=>$price);
echo "3here";
break;
case 5:
$_SESSION['prodcontrolprices'][$num[0]][$num[1]]['subs'][$num[2]][$num[3]]['subs'][$type][$name] = array("price"=>$price);
echo "4here";
break;
}
echo '<br/>';
echo '<pre>';
print_r($_SESSION['prodcontrolprices']);
echo '</pre>';
}else{
$_SESSION['prodcontrolprices'][$type][$name] = array("price"=>$price);
}
}
?>
Below is the output from the echo statements:
Array
(
[0] => Style
[1] => One_sided
)
Contents of Array before values are assigned to it.
Array
(
[Style] => Array
(
[One_sided] => Array
(
[price] => 130.00
[subs] => Array
(
[Quantity] => Array
(
[500] => Array
(
[price] => 10.00
)
[1000] => Array
(
[price] => 20.00
)
)
)
)
)
)
Contents of Array after values are assigned to it.
Array
(
[Style] => Array
(
[One_sided] => Array
(
[price] => 230.00
)
)
)
Upvotes: 0
Views: 738
Reputation: 437376
Your problem is that you are replacing the whole sub-array with a new one (that has just one element):
$_SESSION['prodcontrolprices'][$type][$name] = array("price"=>$price);
What you should do instead is add/replace just one value within it:
$_SESSION['prodcontrolprices'][$type][$name]['price'] = $price;
Upvotes: 4