Pass array from one page to another

后端 未结 4 1504
时光说笑
时光说笑 2021-01-13 04:55

I have an array containing some values, say

arr[\'one\'] = \"one value here\";
arr[\'two\'] = \"second value here\";
arr[\'three\'] = \"third value here\";
         


        
相关标签:
4条回答
  • 2021-01-13 05:28

    The easiest way to do this would be to use the session to store the array from one page to another:

    session_start();
    $_SESSION['array_to_save'] = $arr;
    

    More info on the sessions : http://php.net/manual/en/function.session-start.php

    If you don't want to use session you can do something like this in your first page

    $serialized =htmlspecialchars(serialize($arr));
    echo "<input type=\"hidden\" name=\"ArrayData\" value=\"$serialized\"/>";
    

    and in the other one you retrieve the array data like this :

    $value = unserialize($_POST['ArrayData']);
    

    Solution found here : https://stackoverflow.com/a/3638962/1606729

    0 讨论(0)
  • 2021-01-13 05:32

    home.php file

    session_start();
    if(!empty($arr)){
        $_SESSION['value'] = $arr;
         redirect_to("../detail.php");
    }
    

    detail.php

    session_start();                    
    if(isset($_SESSION['value'])){                           
        foreach ($_SESSION['value'] as $arr) {
            echo $arr . "<br />";
            unset($_SESSION['value']);
        }
    }
    
    0 讨论(0)
  • 2021-01-13 05:34

    If you dont want to use sessions, you can just include the page in the other file.

    file1.php

    <php
        $arr = array();
        $arr['one'] = "one value here";
        $arr['two'] = "second value here";
        $arr['three'] = "third value here";
    ?>
    

    file2.php

    <?php
    
        include "file1.php";
    
        print_r($arr);
    ?>
    

    If the array is dynamically created and you want to pass it through GET or POST you should form the URL on the server side and redirect the user to the HTTP URL page instead of the php file.

    So something like:

    file1.php

    <php
        $arr = array();
        $arr['one'] = "one value here";
        $arr['two'] = "second value here";
        $arr['three'] = "third value here";
    
        $redirect = "http://yoursite.com/file2.php?".http_build_query($arr);
        header( "Location: $redirect" );
    
    ?>
    

    file2.php

    <?php
    
        $params = $_GET;
    
        print_r($params['one']);
        print_r($params['two']);
        print_r($params['three']);
    ?>
    
    0 讨论(0)
  • 2021-01-13 05:39

    You can pass the values by query parameters, too.

    header('Location: detail.php?' . http_build_query($arr, null, '&'));
    

    And you can get the array in the detail.php like this:

    // your values are in the $_GET array
    echo $_GET['one'];  // echoes "one value here" by your example
    

    Be aware that if you pass values by GET or POST (hidden input field), they can be changed by the user easily.

    0 讨论(0)
提交回复
热议问题