Passing a large array between pages in PHP
Is there any way to pas开发者_运维问答s an array between two pages intact?
I am building a huge array, and the building of it uses masses of memmory. I would like to be able to store the array intact and then reaccess it from another page?
If I use $x = print_r($array,true);
and write it to a file, how could I then rebuild it into an array, or is there a better way altogether.
You could easily store that data in the session. Like this
$_SESSION['serialized_data'] = urlencode(serialize($your_data));
and then afterwards on your second page:
$your_data = unserialize(urldecode($_SESSION[$serialized_data]));
I use this approach quite often.
You can store it in session ( not sure how big it is ) .. if you want to write to file .. you can do something like this:
$fp = fopen("file.php" , "w");
fwrite($fp , "<? \$array = ".var_export($array,true).";");
fclose($fp);
and then just include that file like a normal file on next page loads.
Passing huge amounts of data between pages generally isn't a great decision, but there can be exceptions - what are you trying to accomplish here?
I wouldn't suggest using session variables. In many cases, if the data seems to large to pass between pages, it is. In those cases, it may be useful to use a database for the information and access the database from each page.
Easiest way would be to use a session variable.
$_SESSION['big_array']=$big_array;
This wouldn't be particularly advisable if it's a high volume site (as the arrays will sit in memory until sessions expire) but should be fine otherwise.
You'll want to make sure you've started the session prior which, if necessary, can be done using:
session_start();
精彩评论