PHP不能保留对变量所做的更改


PHP Can't keep changes made to a variable

我有一个数组,我保留了一些初始值。在同一页面上,在另一个php标记中,当我按下get_more_items时,我想向数组添加更多的值。

第一个PHP标签

<?php 
   $solution_files = array();
   ... assigning initial values...
?>

在同一页面上,我有另一个php标签,我想修改$solution_files的值:

第二个PHP标签

<?php
     if (isset($_GET["get_more_items"])){   
        //add more values to the $solution_files               
     }
     // new values visible here
?>

在最后一个php标签中,我想列出我的数组($solution_files),我只看到在第一个php标签中分配给它的值,但不是我在搜索(get_more_items)后添加的新值。

第3个PHP标签

<?php
     if (isset($_GET["display_results"])){  
        print_r($solution_files) 
        // it only displays the values I had initially               
     }
?>

当我请求"Get more items"时,我能做些什么来保持我在第二个标签中分配的新值?

你需要创建一个像这样的会话数组

第一个PHP标签

<?php 
   if(!isset($_SESSION['solution_files']))
   {
     $_SESSION['solution_files'] = array();
       ... assigning initial values...
       .. like ..
        $_SESSION['solution_files'][] "some value"; 
    }
?>

第二个PHP标签

<?php 
   if (isset($_GET["get_more_items"])){   
    //add more values to the $solution_files  
       .. like ..
        $_SESSION['solution_files'][] "some more value"; 
    }
?>

第三个PHP标签

<?php 
   if (isset($_GET["display_results"])){  
       print_r($_SESSION['solution_files']) 
       // it only displays the values I had initially               
    }
?>

注意:在php中使用session之前,你必须在页面的顶部启动session。像

session_start();