我无法将新值插入数组。插入元素时,值会发生变化,但不会增加键值。
如果值不在数组中,我想将新值插入数组。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add Cart</title>
</head>
<body>
<div class="container">
<form method="post" action="">
<input type="text" name="salary">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['salary']))
{
$salary = array();
$values = $_POST['salary'];
if(!in_array($values, $salary))
{
array_push($salary, $values);
}
print_r($salary);
}
?>
</div>
</body>
</html>
答案 0 :(得分:0)
这是一个工作示例,说明如何使用$ _SESSION执行您要执行的操作。
<?php
session_start();
if(isset($_POST['salary'])) {
// if you don't check if it exists first
// you will be wiping it every time you post new values
if(!isset($_SESSION['salary'])) {
$_SESSION['salary'] = array();
}
$values = $_POST['salary'];
if(!in_array($values, $_SESSION['salary'])) {
array_push($_SESSION['salary'], $values);
}
// not required but suggested
session_write_close();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Add Cart</title>
</head>
<body>
<div class="container">
<form method="post" action="">
<input type="text" name="salary">
<input type="submit" name="submit" value="submit">
</form>
<h3>Current values stored in salary array</h3>
<?php echo (isset($_SESSION['salary'])) ? json_encode($_SESSION['salary']) : '[]' ?>
</div>
</body>
</html>