【问题标题】:push the values into array using php使用 php 将值推送到数组中
【发布时间】:2015-09-12 11:43:08
【问题描述】:

我无法将新值插入数组。插入元素时,值会发生变化,但不会增加键值。

如果值不在数组中,我想将新值插入到数组中。

<!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>

【问题讨论】:

  • 因为每次重新加载页面时数组都消失了!
  • 如何避免这个问题
  • 你可以使用会话数组$_SESSION
  • 我也试过了,但我无法得到那个解决方案。你能把样品寄给我吗
  • 我是 php 新手。如果我犯了任何错误,请让我知道,请告诉我

标签: php arrays


【解决方案1】:

这是一个如何使用 $_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>

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2017-04-24
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多