我存储在会话变量中的数组有问题。当我尝试更改数组中的特定项目时,整个数组会被新值覆盖。
我的代码如下:
<? 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);
}
}
?>
下面是 echo 语句的输出:
Array
(
[0] => Style
[1] => One_sided
)
数组在赋值之前的内容。
Array
(
[Style] => Array
(
[One_sided] => Array
(
[price] => 130.00
[subs] => Array
(
[Quantity] => Array
(
[500] => Array
(
[price] => 10.00
)
[1000] => Array
(
[price] => 20.00
)
)
)
)
)
)
数组赋值后的内容。
Array
(
[Style] => Array
(
[One_sided] => Array
(
[price] => 230.00
)
)
)