问题
a couple of days ago, I posted here and got a great response on how to handle the arrays. This was exactly what I needed
foreach ($_POST['name'] as $key=>$name) {
echo "Name: $name Age: {$_POST['age'][$key]}";
}
the problem is, I need it not to print but to persist. Im making session variables like $_SESSION["name"]= "some name";
I wanna know how I can dump the POST array from above into a $SESSION[Array]; ultimately, to be able to re dump all of the data at will on any page. I need access to both $name in the array and the $age and I would like them to be associated. In java I would do
String[][] something = new String[10][2]; //10 is size and 2 allows for name at index 0 and age at index 1.
Something things to keep in mind. The size of the POST array is not set. They may be anywhere from 0 inputs to 100.
Along with saving the array, could you please tell me how to access it. Im use to java, so php arrays are new to me.
EDIT
After Trying johnps post
my page looks like this
foreach ($_POST['name'] as $key=>$name) {
echo "Name: $name Age: {$_POST['age'][$key]} <br/>";
$_SESSION['post_data'][$key] = $name;
$_SESSION['post_data'][$key] = $_POST['age'];
echo $key;
}
and the output on the page is
Name: The name potion Age: adult
1
However, Ive tried the following to get "The Name Position" as output and nothing is working
echo $_SESSION['post_data']['name'];//doesnt have an output
echo $_SESSION['post_data'][$key];//out puts "Array" and nothing else
I would like the output to be The name Position, Adult. Just like the foreach loop is doing right now, but from a 2d array. Thanks guys.
回答1:
You can use a multi dimensional array just as easily in PHP. The reason your example doesn't work is because it keeps overriding the same index
//Assuming your POST data consists of age => name pairs, you store it like this
$_SESSION['post_data'] = array();
$count = 0;
foreach ($_POST['name'] as $age => $name) {
$_SESSION['post_data'][$count]['age'] = $age;
$_SESSION['post_data'][$count]['name'] = $name;
$count++;
}
And to access it, simply iterate over it or use the key
//iterating
foreach ($_SESSION['post_data'] as $person) {
echo "Name: {$person['name']} Age: {$person['age']} <br/>";
}
//using the key
echo $_SESSION['post_data'][0]['age']; //print the first person's age
echo $_SESSION['post_data'][0]['name']; //print the first person's name
Visually your data looks like this (example)
array(
0 => array(
age => 12,
name => jane
),
1 => array(
age => 18,
name => jack
),
2 => array(
age => 25,
name => jones
),
)
回答2:
You can directly store $_POST['name'] to $_SESSION["name"] and it will persist,
$_SESSION["name"] = $_POST['name']
来源:https://stackoverflow.com/questions/8462262/altering-arrays-in-php-from-post-to-a-session-variable