douhushen3241 2018-08-22 12:00
浏览 170
已采纳

当我添加它时,PHP数组会被覆盖...为什么? [重复]

This question already has an answer here:

For some reason, whenever I try to add something to my array, it just overwrites the index 0, rather than goingto index 1, 2 etc...

Here's my code

//Saved names
    session_start();
    $saved_names = array();

    $_SESSION['saved_names'] = $saved_names;

    if($_GET['saved_name']){

    $saved_name = $_GET['saved_name'];

    $saved_names[] = $saved_name;        
}
    echo '<pre>', print_r($saved_names, true), '</pre>';
</div>
  • 写回答

3条回答 默认 最新

  • dtlygweb2017 2018-08-22 12:12
    关注

    Others answers are ok-ish, but i like more this solution, it also check if session is just started (so $_SESSION['saved_names'] is not set yet) :

    <?php
    session_start();
    $_SESSION['saved_names'] = isset( $_SESSION['saved_names']) ?  $_SESSION['saved_names'] : [];
    
    if($_GET['saved_name']){
      $_SESSION['saved_names'][] = $_GET['saved_name'];
    }
    echo '<pre>', print_r($_SESSION['saved_names'], true), '</pre>';
    ?>
    

    Edit
    @elitepc solution (as he said) is not working because

    $saved_names = array(); /empty array
    $saved_names = $_SESSION['saved_names'];  / <- it has not been declared also will never update
    

    And then

    $saved_name = $_GET['saved_name'];
    $saved_names[] = $saved_name;
    

    So basically everytime it just creates an empty array and put inside the $_GET value.

    You have to check if the session variable it's been initialized and in case update it with $_GET value

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程